##// END OF EJS Templates
Merged r15536 and r15541 (#23083)....
Jean-Philippe Lang -
r15178:1f79610fdc05
parent child
Show More
@@ -1,820 +1,827
1 # Redmine - project management software
1 # Redmine - project management software
2 # Copyright (C) 2006-2016 Jean-Philippe Lang
2 # Copyright (C) 2006-2016 Jean-Philippe Lang
3 #
3 #
4 # This program is free software; you can redistribute it and/or
4 # This program is free software; you can redistribute it and/or
5 # modify it under the terms of the GNU General Public License
5 # modify it under the terms of the GNU General Public License
6 # as published by the Free Software Foundation; either version 2
6 # as published by the Free Software Foundation; either version 2
7 # of the License, or (at your option) any later version.
7 # of the License, or (at your option) any later version.
8 #
8 #
9 # This program is distributed in the hope that it will be useful,
9 # This program is distributed in the hope that it will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 # GNU General Public License for more details.
12 # GNU General Public License for more details.
13 #
13 #
14 # You should have received a copy of the GNU General Public License
14 # You should have received a copy of the GNU General Public License
15 # along with this program; if not, write to the Free Software
15 # along with this program; if not, write to the Free Software
16 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
16 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17
17
18 require 'uri'
18 require 'uri'
19
19
20 module Redmine
20 module Redmine
21 module FieldFormat
21 module FieldFormat
22 def self.add(name, klass)
22 def self.add(name, klass)
23 all[name.to_s] = klass.instance
23 all[name.to_s] = klass.instance
24 end
24 end
25
25
26 def self.delete(name)
26 def self.delete(name)
27 all.delete(name.to_s)
27 all.delete(name.to_s)
28 end
28 end
29
29
30 def self.all
30 def self.all
31 @formats ||= Hash.new(Base.instance)
31 @formats ||= Hash.new(Base.instance)
32 end
32 end
33
33
34 def self.available_formats
34 def self.available_formats
35 all.keys
35 all.keys
36 end
36 end
37
37
38 def self.find(name)
38 def self.find(name)
39 all[name.to_s]
39 all[name.to_s]
40 end
40 end
41
41
42 # Return an array of custom field formats which can be used in select_tag
42 # Return an array of custom field formats which can be used in select_tag
43 def self.as_select(class_name=nil)
43 def self.as_select(class_name=nil)
44 formats = all.values.select do |format|
44 formats = all.values.select do |format|
45 format.class.customized_class_names.nil? || format.class.customized_class_names.include?(class_name)
45 format.class.customized_class_names.nil? || format.class.customized_class_names.include?(class_name)
46 end
46 end
47 formats.map {|format| [::I18n.t(format.label), format.name] }.sort_by(&:first)
47 formats.map {|format| [::I18n.t(format.label), format.name] }.sort_by(&:first)
48 end
48 end
49
49
50 class Base
50 class Base
51 include Singleton
51 include Singleton
52 include Redmine::I18n
52 include Redmine::I18n
53 include Redmine::Helpers::URL
53 include Redmine::Helpers::URL
54 include ERB::Util
54 include ERB::Util
55
55
56 class_attribute :format_name
56 class_attribute :format_name
57 self.format_name = nil
57 self.format_name = nil
58
58
59 # Set this to true if the format supports multiple values
59 # Set this to true if the format supports multiple values
60 class_attribute :multiple_supported
60 class_attribute :multiple_supported
61 self.multiple_supported = false
61 self.multiple_supported = false
62
62
63 # Set this to true if the format supports textual search on custom values
63 # Set this to true if the format supports textual search on custom values
64 class_attribute :searchable_supported
64 class_attribute :searchable_supported
65 self.searchable_supported = false
65 self.searchable_supported = false
66
66
67 # Set this to true if field values can be summed up
67 # Set this to true if field values can be summed up
68 class_attribute :totalable_supported
68 class_attribute :totalable_supported
69 self.totalable_supported = false
69 self.totalable_supported = false
70
70
71 # Restricts the classes that the custom field can be added to
71 # Restricts the classes that the custom field can be added to
72 # Set to nil for no restrictions
72 # Set to nil for no restrictions
73 class_attribute :customized_class_names
73 class_attribute :customized_class_names
74 self.customized_class_names = nil
74 self.customized_class_names = nil
75
75
76 # Name of the partial for editing the custom field
76 # Name of the partial for editing the custom field
77 class_attribute :form_partial
77 class_attribute :form_partial
78 self.form_partial = nil
78 self.form_partial = nil
79
79
80 class_attribute :change_as_diff
80 class_attribute :change_as_diff
81 self.change_as_diff = false
81 self.change_as_diff = false
82
82
83 def self.add(name)
83 def self.add(name)
84 self.format_name = name
84 self.format_name = name
85 Redmine::FieldFormat.add(name, self)
85 Redmine::FieldFormat.add(name, self)
86 end
86 end
87 private_class_method :add
87 private_class_method :add
88
88
89 def self.field_attributes(*args)
89 def self.field_attributes(*args)
90 CustomField.store_accessor :format_store, *args
90 CustomField.store_accessor :format_store, *args
91 end
91 end
92
92
93 field_attributes :url_pattern
93 field_attributes :url_pattern
94
94
95 def name
95 def name
96 self.class.format_name
96 self.class.format_name
97 end
97 end
98
98
99 def label
99 def label
100 "label_#{name}"
100 "label_#{name}"
101 end
101 end
102
102
103 def cast_custom_value(custom_value)
103 def cast_custom_value(custom_value)
104 cast_value(custom_value.custom_field, custom_value.value, custom_value.customized)
104 cast_value(custom_value.custom_field, custom_value.value, custom_value.customized)
105 end
105 end
106
106
107 def cast_value(custom_field, value, customized=nil)
107 def cast_value(custom_field, value, customized=nil)
108 if value.blank?
108 if value.blank?
109 nil
109 nil
110 elsif value.is_a?(Array)
110 elsif value.is_a?(Array)
111 casted = value.map do |v|
111 casted = value.map do |v|
112 cast_single_value(custom_field, v, customized)
112 cast_single_value(custom_field, v, customized)
113 end
113 end
114 casted.compact.sort
114 casted.compact.sort
115 else
115 else
116 cast_single_value(custom_field, value, customized)
116 cast_single_value(custom_field, value, customized)
117 end
117 end
118 end
118 end
119
119
120 def cast_single_value(custom_field, value, customized=nil)
120 def cast_single_value(custom_field, value, customized=nil)
121 value.to_s
121 value.to_s
122 end
122 end
123
123
124 def target_class
124 def target_class
125 nil
125 nil
126 end
126 end
127
127
128 def possible_custom_value_options(custom_value)
128 def possible_custom_value_options(custom_value)
129 possible_values_options(custom_value.custom_field, custom_value.customized)
129 possible_values_options(custom_value.custom_field, custom_value.customized)
130 end
130 end
131
131
132 def possible_values_options(custom_field, object=nil)
132 def possible_values_options(custom_field, object=nil)
133 []
133 []
134 end
134 end
135
135
136 def value_from_keyword(custom_field, keyword, object)
136 def value_from_keyword(custom_field, keyword, object)
137 possible_values_options = possible_values_options(custom_field, object)
137 possible_values_options = possible_values_options(custom_field, object)
138 if possible_values_options.present?
138 if possible_values_options.present?
139 keyword = keyword.to_s
139 keyword = keyword.to_s
140 if v = possible_values_options.detect {|text, id| keyword.casecmp(text) == 0}
140 if v = possible_values_options.detect {|text, id| keyword.casecmp(text) == 0}
141 if v.is_a?(Array)
141 if v.is_a?(Array)
142 v.last
142 v.last
143 else
143 else
144 v
144 v
145 end
145 end
146 end
146 end
147 else
147 else
148 keyword
148 keyword
149 end
149 end
150 end
150 end
151
151
152 # Returns the validation errors for custom_field
152 # Returns the validation errors for custom_field
153 # Should return an empty array if custom_field is valid
153 # Should return an empty array if custom_field is valid
154 def validate_custom_field(custom_field)
154 def validate_custom_field(custom_field)
155 errors = []
155 errors = []
156 pattern = custom_field.url_pattern
156 pattern = custom_field.url_pattern
157 if pattern.present? && !uri_with_safe_scheme?(url_pattern_without_tokens(pattern))
157 if pattern.present? && !uri_with_safe_scheme?(url_pattern_without_tokens(pattern))
158 errors << [:url_pattern, :invalid]
158 errors << [:url_pattern, :invalid]
159 end
159 end
160 errors
160 errors
161 end
161 end
162
162
163 # Returns the validation error messages for custom_value
163 # Returns the validation error messages for custom_value
164 # Should return an empty array if custom_value is valid
164 # Should return an empty array if custom_value is valid
165 def validate_custom_value(custom_value)
165 def validate_custom_value(custom_value)
166 values = Array.wrap(custom_value.value).reject {|value| value.to_s == ''}
166 values = Array.wrap(custom_value.value).reject {|value| value.to_s == ''}
167 errors = values.map do |value|
167 errors = values.map do |value|
168 validate_single_value(custom_value.custom_field, value, custom_value.customized)
168 validate_single_value(custom_value.custom_field, value, custom_value.customized)
169 end
169 end
170 errors.flatten.uniq
170 errors.flatten.uniq
171 end
171 end
172
172
173 def validate_single_value(custom_field, value, customized=nil)
173 def validate_single_value(custom_field, value, customized=nil)
174 []
174 []
175 end
175 end
176
176
177 def formatted_custom_value(view, custom_value, html=false)
177 def formatted_custom_value(view, custom_value, html=false)
178 formatted_value(view, custom_value.custom_field, custom_value.value, custom_value.customized, html)
178 formatted_value(view, custom_value.custom_field, custom_value.value, custom_value.customized, html)
179 end
179 end
180
180
181 def formatted_value(view, custom_field, value, customized=nil, html=false)
181 def formatted_value(view, custom_field, value, customized=nil, html=false)
182 casted = cast_value(custom_field, value, customized)
182 casted = cast_value(custom_field, value, customized)
183 if html && custom_field.url_pattern.present?
183 if html && custom_field.url_pattern.present?
184 texts_and_urls = Array.wrap(casted).map do |single_value|
184 texts_and_urls = Array.wrap(casted).map do |single_value|
185 text = view.format_object(single_value, false).to_s
185 text = view.format_object(single_value, false).to_s
186 url = url_from_pattern(custom_field, single_value, customized)
186 url = url_from_pattern(custom_field, single_value, customized)
187 [text, url]
187 [text, url]
188 end
188 end
189 links = texts_and_urls.sort_by(&:first).map {|text, url| view.link_to_if uri_with_safe_scheme?(url), text, url}
189 links = texts_and_urls.sort_by(&:first).map {|text, url| view.link_to_if uri_with_safe_scheme?(url), text, url}
190 links.join(', ').html_safe
190 links.join(', ').html_safe
191 else
191 else
192 casted
192 casted
193 end
193 end
194 end
194 end
195
195
196 # Returns an URL generated with the custom field URL pattern
196 # Returns an URL generated with the custom field URL pattern
197 # and variables substitution:
197 # and variables substitution:
198 # %value% => the custom field value
198 # %value% => the custom field value
199 # %id% => id of the customized object
199 # %id% => id of the customized object
200 # %project_id% => id of the project of the customized object if defined
200 # %project_id% => id of the project of the customized object if defined
201 # %project_identifier% => identifier of the project of the customized object if defined
201 # %project_identifier% => identifier of the project of the customized object if defined
202 # %m1%, %m2%... => capture groups matches of the custom field regexp if defined
202 # %m1%, %m2%... => capture groups matches of the custom field regexp if defined
203 def url_from_pattern(custom_field, value, customized)
203 def url_from_pattern(custom_field, value, customized)
204 url = custom_field.url_pattern.to_s.dup
204 url = custom_field.url_pattern.to_s.dup
205 url.gsub!('%value%') {value.to_s}
205 url.gsub!('%value%') {value.to_s}
206 url.gsub!('%id%') {customized.id.to_s}
206 url.gsub!('%id%') {customized.id.to_s}
207 url.gsub!('%project_id%') {(customized.respond_to?(:project) ? customized.project.try(:id) : nil).to_s}
207 url.gsub!('%project_id%') {(customized.respond_to?(:project) ? customized.project.try(:id) : nil).to_s}
208 url.gsub!('%project_identifier%') {(customized.respond_to?(:project) ? customized.project.try(:identifier) : nil).to_s}
208 url.gsub!('%project_identifier%') {(customized.respond_to?(:project) ? customized.project.try(:identifier) : nil).to_s}
209 if custom_field.regexp.present?
209 if custom_field.regexp.present?
210 url.gsub!(%r{%m(\d+)%}) do
210 url.gsub!(%r{%m(\d+)%}) do
211 m = $1.to_i
211 m = $1.to_i
212 if matches ||= value.to_s.match(Regexp.new(custom_field.regexp))
212 if matches ||= value.to_s.match(Regexp.new(custom_field.regexp))
213 matches[m].to_s
213 matches[m].to_s
214 end
214 end
215 end
215 end
216 end
216 end
217 URI.encode(url)
217 URI.encode(url)
218 end
218 end
219 protected :url_from_pattern
219 protected :url_from_pattern
220
220
221 # Returns the URL pattern with substitution tokens removed,
221 # Returns the URL pattern with substitution tokens removed,
222 # for validation purpose
222 # for validation purpose
223 def url_pattern_without_tokens(url_pattern)
223 def url_pattern_without_tokens(url_pattern)
224 url_pattern.to_s.gsub(/%(value|id|project_id|project_identifier|m\d+)%/, '')
224 url_pattern.to_s.gsub(/%(value|id|project_id|project_identifier|m\d+)%/, '')
225 end
225 end
226 protected :url_pattern_without_tokens
226 protected :url_pattern_without_tokens
227
227
228 def edit_tag(view, tag_id, tag_name, custom_value, options={})
228 def edit_tag(view, tag_id, tag_name, custom_value, options={})
229 view.text_field_tag(tag_name, custom_value.value, options.merge(:id => tag_id))
229 view.text_field_tag(tag_name, custom_value.value, options.merge(:id => tag_id))
230 end
230 end
231
231
232 def bulk_edit_tag(view, tag_id, tag_name, custom_field, objects, value, options={})
232 def bulk_edit_tag(view, tag_id, tag_name, custom_field, objects, value, options={})
233 view.text_field_tag(tag_name, value, options.merge(:id => tag_id)) +
233 view.text_field_tag(tag_name, value, options.merge(:id => tag_id)) +
234 bulk_clear_tag(view, tag_id, tag_name, custom_field, value)
234 bulk_clear_tag(view, tag_id, tag_name, custom_field, value)
235 end
235 end
236
236
237 def bulk_clear_tag(view, tag_id, tag_name, custom_field, value)
237 def bulk_clear_tag(view, tag_id, tag_name, custom_field, value)
238 if custom_field.is_required?
238 if custom_field.is_required?
239 ''.html_safe
239 ''.html_safe
240 else
240 else
241 view.content_tag('label',
241 view.content_tag('label',
242 view.check_box_tag(tag_name, '__none__', (value == '__none__'), :id => nil, :data => {:disables => "##{tag_id}"}) + l(:button_clear),
242 view.check_box_tag(tag_name, '__none__', (value == '__none__'), :id => nil, :data => {:disables => "##{tag_id}"}) + l(:button_clear),
243 :class => 'inline'
243 :class => 'inline'
244 )
244 )
245 end
245 end
246 end
246 end
247 protected :bulk_clear_tag
247 protected :bulk_clear_tag
248
248
249 def query_filter_options(custom_field, query)
249 def query_filter_options(custom_field, query)
250 {:type => :string}
250 {:type => :string}
251 end
251 end
252
252
253 def before_custom_field_save(custom_field)
253 def before_custom_field_save(custom_field)
254 end
254 end
255
255
256 # Returns a ORDER BY clause that can used to sort customized
256 # Returns a ORDER BY clause that can used to sort customized
257 # objects by their value of the custom field.
257 # objects by their value of the custom field.
258 # Returns nil if the custom field can not be used for sorting.
258 # Returns nil if the custom field can not be used for sorting.
259 def order_statement(custom_field)
259 def order_statement(custom_field)
260 # COALESCE is here to make sure that blank and NULL values are sorted equally
260 # COALESCE is here to make sure that blank and NULL values are sorted equally
261 "COALESCE(#{join_alias custom_field}.value, '')"
261 "COALESCE(#{join_alias custom_field}.value, '')"
262 end
262 end
263
263
264 # Returns a GROUP BY clause that can used to group by custom value
264 # Returns a GROUP BY clause that can used to group by custom value
265 # Returns nil if the custom field can not be used for grouping.
265 # Returns nil if the custom field can not be used for grouping.
266 def group_statement(custom_field)
266 def group_statement(custom_field)
267 nil
267 nil
268 end
268 end
269
269
270 # Returns a JOIN clause that is added to the query when sorting by custom values
270 # Returns a JOIN clause that is added to the query when sorting by custom values
271 def join_for_order_statement(custom_field)
271 def join_for_order_statement(custom_field)
272 alias_name = join_alias(custom_field)
272 alias_name = join_alias(custom_field)
273
273
274 "LEFT OUTER JOIN #{CustomValue.table_name} #{alias_name}" +
274 "LEFT OUTER JOIN #{CustomValue.table_name} #{alias_name}" +
275 " ON #{alias_name}.customized_type = '#{custom_field.class.customized_class.base_class.name}'" +
275 " ON #{alias_name}.customized_type = '#{custom_field.class.customized_class.base_class.name}'" +
276 " AND #{alias_name}.customized_id = #{custom_field.class.customized_class.table_name}.id" +
276 " AND #{alias_name}.customized_id = #{custom_field.class.customized_class.table_name}.id" +
277 " AND #{alias_name}.custom_field_id = #{custom_field.id}" +
277 " AND #{alias_name}.custom_field_id = #{custom_field.id}" +
278 " AND (#{custom_field.visibility_by_project_condition})" +
278 " AND (#{custom_field.visibility_by_project_condition})" +
279 " AND #{alias_name}.value <> ''" +
279 " AND #{alias_name}.value <> ''" +
280 " AND #{alias_name}.id = (SELECT max(#{alias_name}_2.id) FROM #{CustomValue.table_name} #{alias_name}_2" +
280 " AND #{alias_name}.id = (SELECT max(#{alias_name}_2.id) FROM #{CustomValue.table_name} #{alias_name}_2" +
281 " WHERE #{alias_name}_2.customized_type = #{alias_name}.customized_type" +
281 " WHERE #{alias_name}_2.customized_type = #{alias_name}.customized_type" +
282 " AND #{alias_name}_2.customized_id = #{alias_name}.customized_id" +
282 " AND #{alias_name}_2.customized_id = #{alias_name}.customized_id" +
283 " AND #{alias_name}_2.custom_field_id = #{alias_name}.custom_field_id)"
283 " AND #{alias_name}_2.custom_field_id = #{alias_name}.custom_field_id)"
284 end
284 end
285
285
286 def join_alias(custom_field)
286 def join_alias(custom_field)
287 "cf_#{custom_field.id}"
287 "cf_#{custom_field.id}"
288 end
288 end
289 protected :join_alias
289 protected :join_alias
290 end
290 end
291
291
292 class Unbounded < Base
292 class Unbounded < Base
293 def validate_single_value(custom_field, value, customized=nil)
293 def validate_single_value(custom_field, value, customized=nil)
294 errs = super
294 errs = super
295 value = value.to_s
295 value = value.to_s
296 unless custom_field.regexp.blank? or value =~ Regexp.new(custom_field.regexp)
296 unless custom_field.regexp.blank? or value =~ Regexp.new(custom_field.regexp)
297 errs << ::I18n.t('activerecord.errors.messages.invalid')
297 errs << ::I18n.t('activerecord.errors.messages.invalid')
298 end
298 end
299 if custom_field.min_length && value.length < custom_field.min_length
299 if custom_field.min_length && value.length < custom_field.min_length
300 errs << ::I18n.t('activerecord.errors.messages.too_short', :count => custom_field.min_length)
300 errs << ::I18n.t('activerecord.errors.messages.too_short', :count => custom_field.min_length)
301 end
301 end
302 if custom_field.max_length && custom_field.max_length > 0 && value.length > custom_field.max_length
302 if custom_field.max_length && custom_field.max_length > 0 && value.length > custom_field.max_length
303 errs << ::I18n.t('activerecord.errors.messages.too_long', :count => custom_field.max_length)
303 errs << ::I18n.t('activerecord.errors.messages.too_long', :count => custom_field.max_length)
304 end
304 end
305 errs
305 errs
306 end
306 end
307 end
307 end
308
308
309 class StringFormat < Unbounded
309 class StringFormat < Unbounded
310 add 'string'
310 add 'string'
311 self.searchable_supported = true
311 self.searchable_supported = true
312 self.form_partial = 'custom_fields/formats/string'
312 self.form_partial = 'custom_fields/formats/string'
313 field_attributes :text_formatting
313 field_attributes :text_formatting
314
314
315 def formatted_value(view, custom_field, value, customized=nil, html=false)
315 def formatted_value(view, custom_field, value, customized=nil, html=false)
316 if html
316 if html
317 if custom_field.url_pattern.present?
317 if custom_field.url_pattern.present?
318 super
318 super
319 elsif custom_field.text_formatting == 'full'
319 elsif custom_field.text_formatting == 'full'
320 view.textilizable(value, :object => customized)
320 view.textilizable(value, :object => customized)
321 else
321 else
322 value.to_s
322 value.to_s
323 end
323 end
324 else
324 else
325 value.to_s
325 value.to_s
326 end
326 end
327 end
327 end
328 end
328 end
329
329
330 class TextFormat < Unbounded
330 class TextFormat < Unbounded
331 add 'text'
331 add 'text'
332 self.searchable_supported = true
332 self.searchable_supported = true
333 self.form_partial = 'custom_fields/formats/text'
333 self.form_partial = 'custom_fields/formats/text'
334 self.change_as_diff = true
334 self.change_as_diff = true
335
335
336 def formatted_value(view, custom_field, value, customized=nil, html=false)
336 def formatted_value(view, custom_field, value, customized=nil, html=false)
337 if html
337 if html
338 if value.present?
338 if value.present?
339 if custom_field.text_formatting == 'full'
339 if custom_field.text_formatting == 'full'
340 view.textilizable(value, :object => customized)
340 view.textilizable(value, :object => customized)
341 else
341 else
342 view.simple_format(html_escape(value))
342 view.simple_format(html_escape(value))
343 end
343 end
344 else
344 else
345 ''
345 ''
346 end
346 end
347 else
347 else
348 value.to_s
348 value.to_s
349 end
349 end
350 end
350 end
351
351
352 def edit_tag(view, tag_id, tag_name, custom_value, options={})
352 def edit_tag(view, tag_id, tag_name, custom_value, options={})
353 view.text_area_tag(tag_name, custom_value.value, options.merge(:id => tag_id, :rows => 3))
353 view.text_area_tag(tag_name, custom_value.value, options.merge(:id => tag_id, :rows => 3))
354 end
354 end
355
355
356 def bulk_edit_tag(view, tag_id, tag_name, custom_field, objects, value, options={})
356 def bulk_edit_tag(view, tag_id, tag_name, custom_field, objects, value, options={})
357 view.text_area_tag(tag_name, value, options.merge(:id => tag_id, :rows => 3)) +
357 view.text_area_tag(tag_name, value, options.merge(:id => tag_id, :rows => 3)) +
358 '<br />'.html_safe +
358 '<br />'.html_safe +
359 bulk_clear_tag(view, tag_id, tag_name, custom_field, value)
359 bulk_clear_tag(view, tag_id, tag_name, custom_field, value)
360 end
360 end
361
361
362 def query_filter_options(custom_field, query)
362 def query_filter_options(custom_field, query)
363 {:type => :text}
363 {:type => :text}
364 end
364 end
365 end
365 end
366
366
367 class LinkFormat < StringFormat
367 class LinkFormat < StringFormat
368 add 'link'
368 add 'link'
369 self.searchable_supported = false
369 self.searchable_supported = false
370 self.form_partial = 'custom_fields/formats/link'
370 self.form_partial = 'custom_fields/formats/link'
371
371
372 def formatted_value(view, custom_field, value, customized=nil, html=false)
372 def formatted_value(view, custom_field, value, customized=nil, html=false)
373 if html && value.present?
373 if html && value.present?
374 if custom_field.url_pattern.present?
374 if custom_field.url_pattern.present?
375 url = url_from_pattern(custom_field, value, customized)
375 url = url_from_pattern(custom_field, value, customized)
376 else
376 else
377 url = value.to_s
377 url = value.to_s
378 unless url =~ %r{\A[a-z]+://}i
378 unless url =~ %r{\A[a-z]+://}i
379 # no protocol found, use http by default
379 # no protocol found, use http by default
380 url = "http://" + url
380 url = "http://" + url
381 end
381 end
382 end
382 end
383 view.link_to value.to_s.truncate(40), url
383 view.link_to value.to_s.truncate(40), url
384 else
384 else
385 value.to_s
385 value.to_s
386 end
386 end
387 end
387 end
388 end
388 end
389
389
390 class Numeric < Unbounded
390 class Numeric < Unbounded
391 self.form_partial = 'custom_fields/formats/numeric'
391 self.form_partial = 'custom_fields/formats/numeric'
392 self.totalable_supported = true
392 self.totalable_supported = true
393
393
394 def order_statement(custom_field)
394 def order_statement(custom_field)
395 # Make the database cast values into numeric
395 # Make the database cast values into numeric
396 # Postgresql will raise an error if a value can not be casted!
396 # Postgresql will raise an error if a value can not be casted!
397 # CustomValue validations should ensure that it doesn't occur
397 # CustomValue validations should ensure that it doesn't occur
398 "CAST(CASE #{join_alias custom_field}.value WHEN '' THEN '0' ELSE #{join_alias custom_field}.value END AS decimal(30,3))"
398 "CAST(CASE #{join_alias custom_field}.value WHEN '' THEN '0' ELSE #{join_alias custom_field}.value END AS decimal(30,3))"
399 end
399 end
400
400
401 # Returns totals for the given scope
401 # Returns totals for the given scope
402 def total_for_scope(custom_field, scope)
402 def total_for_scope(custom_field, scope)
403 scope.joins(:custom_values).
403 scope.joins(:custom_values).
404 where(:custom_values => {:custom_field_id => custom_field.id}).
404 where(:custom_values => {:custom_field_id => custom_field.id}).
405 where.not(:custom_values => {:value => ''}).
405 where.not(:custom_values => {:value => ''}).
406 sum("CAST(#{CustomValue.table_name}.value AS decimal(30,3))")
406 sum("CAST(#{CustomValue.table_name}.value AS decimal(30,3))")
407 end
407 end
408
408
409 def cast_total_value(custom_field, value)
409 def cast_total_value(custom_field, value)
410 cast_single_value(custom_field, value)
410 cast_single_value(custom_field, value)
411 end
411 end
412 end
412 end
413
413
414 class IntFormat < Numeric
414 class IntFormat < Numeric
415 add 'int'
415 add 'int'
416
416
417 def label
417 def label
418 "label_integer"
418 "label_integer"
419 end
419 end
420
420
421 def cast_single_value(custom_field, value, customized=nil)
421 def cast_single_value(custom_field, value, customized=nil)
422 value.to_i
422 value.to_i
423 end
423 end
424
424
425 def validate_single_value(custom_field, value, customized=nil)
425 def validate_single_value(custom_field, value, customized=nil)
426 errs = super
426 errs = super
427 errs << ::I18n.t('activerecord.errors.messages.not_a_number') unless value.to_s =~ /^[+-]?\d+$/
427 errs << ::I18n.t('activerecord.errors.messages.not_a_number') unless value.to_s =~ /^[+-]?\d+$/
428 errs
428 errs
429 end
429 end
430
430
431 def query_filter_options(custom_field, query)
431 def query_filter_options(custom_field, query)
432 {:type => :integer}
432 {:type => :integer}
433 end
433 end
434
434
435 def group_statement(custom_field)
435 def group_statement(custom_field)
436 order_statement(custom_field)
436 order_statement(custom_field)
437 end
437 end
438 end
438 end
439
439
440 class FloatFormat < Numeric
440 class FloatFormat < Numeric
441 add 'float'
441 add 'float'
442
442
443 def cast_single_value(custom_field, value, customized=nil)
443 def cast_single_value(custom_field, value, customized=nil)
444 value.to_f
444 value.to_f
445 end
445 end
446
446
447 def cast_total_value(custom_field, value)
447 def cast_total_value(custom_field, value)
448 value.to_f.round(2)
448 value.to_f.round(2)
449 end
449 end
450
450
451 def validate_single_value(custom_field, value, customized=nil)
451 def validate_single_value(custom_field, value, customized=nil)
452 errs = super
452 errs = super
453 errs << ::I18n.t('activerecord.errors.messages.invalid') unless (Kernel.Float(value) rescue nil)
453 errs << ::I18n.t('activerecord.errors.messages.invalid') unless (Kernel.Float(value) rescue nil)
454 errs
454 errs
455 end
455 end
456
456
457 def query_filter_options(custom_field, query)
457 def query_filter_options(custom_field, query)
458 {:type => :float}
458 {:type => :float}
459 end
459 end
460 end
460 end
461
461
462 class DateFormat < Unbounded
462 class DateFormat < Unbounded
463 add 'date'
463 add 'date'
464 self.form_partial = 'custom_fields/formats/date'
464 self.form_partial = 'custom_fields/formats/date'
465
465
466 def cast_single_value(custom_field, value, customized=nil)
466 def cast_single_value(custom_field, value, customized=nil)
467 value.to_date rescue nil
467 value.to_date rescue nil
468 end
468 end
469
469
470 def validate_single_value(custom_field, value, customized=nil)
470 def validate_single_value(custom_field, value, customized=nil)
471 if value =~ /^\d{4}-\d{2}-\d{2}$/ && (value.to_date rescue false)
471 if value =~ /^\d{4}-\d{2}-\d{2}$/ && (value.to_date rescue false)
472 []
472 []
473 else
473 else
474 [::I18n.t('activerecord.errors.messages.not_a_date')]
474 [::I18n.t('activerecord.errors.messages.not_a_date')]
475 end
475 end
476 end
476 end
477
477
478 def edit_tag(view, tag_id, tag_name, custom_value, options={})
478 def edit_tag(view, tag_id, tag_name, custom_value, options={})
479 view.date_field_tag(tag_name, custom_value.value, options.merge(:id => tag_id, :size => 10)) +
479 view.date_field_tag(tag_name, custom_value.value, options.merge(:id => tag_id, :size => 10)) +
480 view.calendar_for(tag_id)
480 view.calendar_for(tag_id)
481 end
481 end
482
482
483 def bulk_edit_tag(view, tag_id, tag_name, custom_field, objects, value, options={})
483 def bulk_edit_tag(view, tag_id, tag_name, custom_field, objects, value, options={})
484 view.date_field_tag(tag_name, value, options.merge(:id => tag_id, :size => 10)) +
484 view.date_field_tag(tag_name, value, options.merge(:id => tag_id, :size => 10)) +
485 view.calendar_for(tag_id) +
485 view.calendar_for(tag_id) +
486 bulk_clear_tag(view, tag_id, tag_name, custom_field, value)
486 bulk_clear_tag(view, tag_id, tag_name, custom_field, value)
487 end
487 end
488
488
489 def query_filter_options(custom_field, query)
489 def query_filter_options(custom_field, query)
490 {:type => :date}
490 {:type => :date}
491 end
491 end
492
492
493 def group_statement(custom_field)
493 def group_statement(custom_field)
494 order_statement(custom_field)
494 order_statement(custom_field)
495 end
495 end
496 end
496 end
497
497
498 class List < Base
498 class List < Base
499 self.multiple_supported = true
499 self.multiple_supported = true
500 field_attributes :edit_tag_style
500 field_attributes :edit_tag_style
501
501
502 def edit_tag(view, tag_id, tag_name, custom_value, options={})
502 def edit_tag(view, tag_id, tag_name, custom_value, options={})
503 if custom_value.custom_field.edit_tag_style == 'check_box'
503 if custom_value.custom_field.edit_tag_style == 'check_box'
504 check_box_edit_tag(view, tag_id, tag_name, custom_value, options)
504 check_box_edit_tag(view, tag_id, tag_name, custom_value, options)
505 else
505 else
506 select_edit_tag(view, tag_id, tag_name, custom_value, options)
506 select_edit_tag(view, tag_id, tag_name, custom_value, options)
507 end
507 end
508 end
508 end
509
509
510 def bulk_edit_tag(view, tag_id, tag_name, custom_field, objects, value, options={})
510 def bulk_edit_tag(view, tag_id, tag_name, custom_field, objects, value, options={})
511 opts = []
511 opts = []
512 opts << [l(:label_no_change_option), ''] unless custom_field.multiple?
512 opts << [l(:label_no_change_option), ''] unless custom_field.multiple?
513 opts << [l(:label_none), '__none__'] unless custom_field.is_required?
513 opts << [l(:label_none), '__none__'] unless custom_field.is_required?
514 opts += possible_values_options(custom_field, objects)
514 opts += possible_values_options(custom_field, objects)
515 view.select_tag(tag_name, view.options_for_select(opts, value), options.merge(:multiple => custom_field.multiple?))
515 view.select_tag(tag_name, view.options_for_select(opts, value), options.merge(:multiple => custom_field.multiple?))
516 end
516 end
517
517
518 def query_filter_options(custom_field, query)
518 def query_filter_options(custom_field, query)
519 {:type => :list_optional, :values => query_filter_values(custom_field, query)}
519 {:type => :list_optional, :values => query_filter_values(custom_field, query)}
520 end
520 end
521
521
522 protected
522 protected
523
523
524 # Returns the values that are available in the field filter
524 # Returns the values that are available in the field filter
525 def query_filter_values(custom_field, query)
525 def query_filter_values(custom_field, query)
526 possible_values_options(custom_field, query.project)
526 possible_values_options(custom_field, query.project)
527 end
527 end
528
528
529 # Renders the edit tag as a select tag
529 # Renders the edit tag as a select tag
530 def select_edit_tag(view, tag_id, tag_name, custom_value, options={})
530 def select_edit_tag(view, tag_id, tag_name, custom_value, options={})
531 blank_option = ''.html_safe
531 blank_option = ''.html_safe
532 unless custom_value.custom_field.multiple?
532 unless custom_value.custom_field.multiple?
533 if custom_value.custom_field.is_required?
533 if custom_value.custom_field.is_required?
534 unless custom_value.custom_field.default_value.present?
534 unless custom_value.custom_field.default_value.present?
535 blank_option = view.content_tag('option', "--- #{l(:actionview_instancetag_blank_option)} ---", :value => '')
535 blank_option = view.content_tag('option', "--- #{l(:actionview_instancetag_blank_option)} ---", :value => '')
536 end
536 end
537 else
537 else
538 blank_option = view.content_tag('option', '&nbsp;'.html_safe, :value => '')
538 blank_option = view.content_tag('option', '&nbsp;'.html_safe, :value => '')
539 end
539 end
540 end
540 end
541 options_tags = blank_option + view.options_for_select(possible_custom_value_options(custom_value), custom_value.value)
541 options_tags = blank_option + view.options_for_select(possible_custom_value_options(custom_value), custom_value.value)
542 s = view.select_tag(tag_name, options_tags, options.merge(:id => tag_id, :multiple => custom_value.custom_field.multiple?))
542 s = view.select_tag(tag_name, options_tags, options.merge(:id => tag_id, :multiple => custom_value.custom_field.multiple?))
543 if custom_value.custom_field.multiple?
543 if custom_value.custom_field.multiple?
544 s << view.hidden_field_tag(tag_name, '')
544 s << view.hidden_field_tag(tag_name, '')
545 end
545 end
546 s
546 s
547 end
547 end
548
548
549 # Renders the edit tag as check box or radio tags
549 # Renders the edit tag as check box or radio tags
550 def check_box_edit_tag(view, tag_id, tag_name, custom_value, options={})
550 def check_box_edit_tag(view, tag_id, tag_name, custom_value, options={})
551 opts = []
551 opts = []
552 unless custom_value.custom_field.multiple? || custom_value.custom_field.is_required?
552 unless custom_value.custom_field.multiple? || custom_value.custom_field.is_required?
553 opts << ["(#{l(:label_none)})", '']
553 opts << ["(#{l(:label_none)})", '']
554 end
554 end
555 opts += possible_custom_value_options(custom_value)
555 opts += possible_custom_value_options(custom_value)
556 s = ''.html_safe
556 s = ''.html_safe
557 tag_method = custom_value.custom_field.multiple? ? :check_box_tag : :radio_button_tag
557 tag_method = custom_value.custom_field.multiple? ? :check_box_tag : :radio_button_tag
558 opts.each do |label, value|
558 opts.each do |label, value|
559 value ||= label
559 value ||= label
560 checked = (custom_value.value.is_a?(Array) && custom_value.value.include?(value)) || custom_value.value.to_s == value
560 checked = (custom_value.value.is_a?(Array) && custom_value.value.include?(value)) || custom_value.value.to_s == value
561 tag = view.send(tag_method, tag_name, value, checked, :id => tag_id)
561 tag = view.send(tag_method, tag_name, value, checked, :id => tag_id)
562 # set the id on the first tag only
562 # set the id on the first tag only
563 tag_id = nil
563 tag_id = nil
564 s << view.content_tag('label', tag + ' ' + label)
564 s << view.content_tag('label', tag + ' ' + label)
565 end
565 end
566 if custom_value.custom_field.multiple?
566 if custom_value.custom_field.multiple?
567 s << view.hidden_field_tag(tag_name, '')
567 s << view.hidden_field_tag(tag_name, '')
568 end
568 end
569 css = "#{options[:class]} check_box_group"
569 css = "#{options[:class]} check_box_group"
570 view.content_tag('span', s, options.merge(:class => css))
570 view.content_tag('span', s, options.merge(:class => css))
571 end
571 end
572 end
572 end
573
573
574 class ListFormat < List
574 class ListFormat < List
575 add 'list'
575 add 'list'
576 self.searchable_supported = true
576 self.searchable_supported = true
577 self.form_partial = 'custom_fields/formats/list'
577 self.form_partial = 'custom_fields/formats/list'
578
578
579 def possible_custom_value_options(custom_value)
579 def possible_custom_value_options(custom_value)
580 options = possible_values_options(custom_value.custom_field)
580 options = possible_values_options(custom_value.custom_field)
581 missing = [custom_value.value].flatten.reject(&:blank?) - options
581 missing = [custom_value.value].flatten.reject(&:blank?) - options
582 if missing.any?
582 if missing.any?
583 options += missing
583 options += missing
584 end
584 end
585 options
585 options
586 end
586 end
587
587
588 def possible_values_options(custom_field, object=nil)
588 def possible_values_options(custom_field, object=nil)
589 custom_field.possible_values
589 custom_field.possible_values
590 end
590 end
591
591
592 def validate_custom_field(custom_field)
592 def validate_custom_field(custom_field)
593 errors = []
593 errors = []
594 errors << [:possible_values, :blank] if custom_field.possible_values.blank?
594 errors << [:possible_values, :blank] if custom_field.possible_values.blank?
595 errors << [:possible_values, :invalid] unless custom_field.possible_values.is_a? Array
595 errors << [:possible_values, :invalid] unless custom_field.possible_values.is_a? Array
596 errors
596 errors
597 end
597 end
598
598
599 def validate_custom_value(custom_value)
599 def validate_custom_value(custom_value)
600 values = Array.wrap(custom_value.value).reject {|value| value.to_s == ''}
600 values = Array.wrap(custom_value.value).reject {|value| value.to_s == ''}
601 invalid_values = values - Array.wrap(custom_value.value_was) - custom_value.custom_field.possible_values
601 invalid_values = values - Array.wrap(custom_value.value_was) - custom_value.custom_field.possible_values
602 if invalid_values.any?
602 if invalid_values.any?
603 [::I18n.t('activerecord.errors.messages.inclusion')]
603 [::I18n.t('activerecord.errors.messages.inclusion')]
604 else
604 else
605 []
605 []
606 end
606 end
607 end
607 end
608
608
609 def group_statement(custom_field)
609 def group_statement(custom_field)
610 order_statement(custom_field)
610 order_statement(custom_field)
611 end
611 end
612 end
612 end
613
613
614 class BoolFormat < List
614 class BoolFormat < List
615 add 'bool'
615 add 'bool'
616 self.multiple_supported = false
616 self.multiple_supported = false
617 self.form_partial = 'custom_fields/formats/bool'
617 self.form_partial = 'custom_fields/formats/bool'
618
618
619 def label
619 def label
620 "label_boolean"
620 "label_boolean"
621 end
621 end
622
622
623 def cast_single_value(custom_field, value, customized=nil)
623 def cast_single_value(custom_field, value, customized=nil)
624 value == '1' ? true : false
624 value == '1' ? true : false
625 end
625 end
626
626
627 def possible_values_options(custom_field, object=nil)
627 def possible_values_options(custom_field, object=nil)
628 [[::I18n.t(:general_text_Yes), '1'], [::I18n.t(:general_text_No), '0']]
628 [[::I18n.t(:general_text_Yes), '1'], [::I18n.t(:general_text_No), '0']]
629 end
629 end
630
630
631 def group_statement(custom_field)
631 def group_statement(custom_field)
632 order_statement(custom_field)
632 order_statement(custom_field)
633 end
633 end
634
634
635 def edit_tag(view, tag_id, tag_name, custom_value, options={})
635 def edit_tag(view, tag_id, tag_name, custom_value, options={})
636 case custom_value.custom_field.edit_tag_style
636 case custom_value.custom_field.edit_tag_style
637 when 'check_box'
637 when 'check_box'
638 single_check_box_edit_tag(view, tag_id, tag_name, custom_value, options)
638 single_check_box_edit_tag(view, tag_id, tag_name, custom_value, options)
639 when 'radio'
639 when 'radio'
640 check_box_edit_tag(view, tag_id, tag_name, custom_value, options)
640 check_box_edit_tag(view, tag_id, tag_name, custom_value, options)
641 else
641 else
642 select_edit_tag(view, tag_id, tag_name, custom_value, options)
642 select_edit_tag(view, tag_id, tag_name, custom_value, options)
643 end
643 end
644 end
644 end
645
645
646 # Renders the edit tag as a simple check box
646 # Renders the edit tag as a simple check box
647 def single_check_box_edit_tag(view, tag_id, tag_name, custom_value, options={})
647 def single_check_box_edit_tag(view, tag_id, tag_name, custom_value, options={})
648 s = ''.html_safe
648 s = ''.html_safe
649 s << view.hidden_field_tag(tag_name, '0', :id => nil)
649 s << view.hidden_field_tag(tag_name, '0', :id => nil)
650 s << view.check_box_tag(tag_name, '1', custom_value.value.to_s == '1', :id => tag_id)
650 s << view.check_box_tag(tag_name, '1', custom_value.value.to_s == '1', :id => tag_id)
651 view.content_tag('span', s, options)
651 view.content_tag('span', s, options)
652 end
652 end
653 end
653 end
654
654
655 class RecordList < List
655 class RecordList < List
656 self.customized_class_names = %w(Issue TimeEntry Version Document Project)
656 self.customized_class_names = %w(Issue TimeEntry Version Document Project)
657
657
658 def cast_single_value(custom_field, value, customized=nil)
658 def cast_single_value(custom_field, value, customized=nil)
659 target_class.find_by_id(value.to_i) if value.present?
659 target_class.find_by_id(value.to_i) if value.present?
660 end
660 end
661
661
662 def target_class
662 def target_class
663 @target_class ||= self.class.name[/^(.*::)?(.+)Format$/, 2].constantize rescue nil
663 @target_class ||= self.class.name[/^(.*::)?(.+)Format$/, 2].constantize rescue nil
664 end
664 end
665
665
666 def reset_target_class
666 def reset_target_class
667 @target_class = nil
667 @target_class = nil
668 end
668 end
669
669
670 def possible_custom_value_options(custom_value)
670 def possible_custom_value_options(custom_value)
671 options = possible_values_options(custom_value.custom_field, custom_value.customized)
671 options = possible_values_options(custom_value.custom_field, custom_value.customized)
672 missing = [custom_value.value_was].flatten.reject(&:blank?) - options.map(&:last)
672 missing = [custom_value.value_was].flatten.reject(&:blank?) - options.map(&:last)
673 if missing.any?
673 if missing.any?
674 options += target_class.where(:id => missing.map(&:to_i)).map {|o| [o.to_s, o.id.to_s]}
674 options += target_class.where(:id => missing.map(&:to_i)).map {|o| [o.to_s, o.id.to_s]}
675 end
675 end
676 options
676 options
677 end
677 end
678
678
679 def order_statement(custom_field)
679 def order_statement(custom_field)
680 if target_class.respond_to?(:fields_for_order_statement)
680 if target_class.respond_to?(:fields_for_order_statement)
681 target_class.fields_for_order_statement(value_join_alias(custom_field))
681 target_class.fields_for_order_statement(value_join_alias(custom_field))
682 end
682 end
683 end
683 end
684
684
685 def group_statement(custom_field)
685 def group_statement(custom_field)
686 "COALESCE(#{join_alias custom_field}.value, '')"
686 "COALESCE(#{join_alias custom_field}.value, '')"
687 end
687 end
688
688
689 def join_for_order_statement(custom_field)
689 def join_for_order_statement(custom_field)
690 alias_name = join_alias(custom_field)
690 alias_name = join_alias(custom_field)
691
691
692 "LEFT OUTER JOIN #{CustomValue.table_name} #{alias_name}" +
692 "LEFT OUTER JOIN #{CustomValue.table_name} #{alias_name}" +
693 " ON #{alias_name}.customized_type = '#{custom_field.class.customized_class.base_class.name}'" +
693 " ON #{alias_name}.customized_type = '#{custom_field.class.customized_class.base_class.name}'" +
694 " AND #{alias_name}.customized_id = #{custom_field.class.customized_class.table_name}.id" +
694 " AND #{alias_name}.customized_id = #{custom_field.class.customized_class.table_name}.id" +
695 " AND #{alias_name}.custom_field_id = #{custom_field.id}" +
695 " AND #{alias_name}.custom_field_id = #{custom_field.id}" +
696 " AND (#{custom_field.visibility_by_project_condition})" +
696 " AND (#{custom_field.visibility_by_project_condition})" +
697 " AND #{alias_name}.value <> ''" +
697 " AND #{alias_name}.value <> ''" +
698 " AND #{alias_name}.id = (SELECT max(#{alias_name}_2.id) FROM #{CustomValue.table_name} #{alias_name}_2" +
698 " AND #{alias_name}.id = (SELECT max(#{alias_name}_2.id) FROM #{CustomValue.table_name} #{alias_name}_2" +
699 " WHERE #{alias_name}_2.customized_type = #{alias_name}.customized_type" +
699 " WHERE #{alias_name}_2.customized_type = #{alias_name}.customized_type" +
700 " AND #{alias_name}_2.customized_id = #{alias_name}.customized_id" +
700 " AND #{alias_name}_2.customized_id = #{alias_name}.customized_id" +
701 " AND #{alias_name}_2.custom_field_id = #{alias_name}.custom_field_id)" +
701 " AND #{alias_name}_2.custom_field_id = #{alias_name}.custom_field_id)" +
702 " LEFT OUTER JOIN #{target_class.table_name} #{value_join_alias custom_field}" +
702 " LEFT OUTER JOIN #{target_class.table_name} #{value_join_alias custom_field}" +
703 " ON CAST(CASE #{alias_name}.value WHEN '' THEN '0' ELSE #{alias_name}.value END AS decimal(30,0)) = #{value_join_alias custom_field}.id"
703 " ON CAST(CASE #{alias_name}.value WHEN '' THEN '0' ELSE #{alias_name}.value END AS decimal(30,0)) = #{value_join_alias custom_field}.id"
704 end
704 end
705
705
706 def value_join_alias(custom_field)
706 def value_join_alias(custom_field)
707 join_alias(custom_field) + "_" + custom_field.field_format
707 join_alias(custom_field) + "_" + custom_field.field_format
708 end
708 end
709 protected :value_join_alias
709 protected :value_join_alias
710 end
710 end
711
711
712 class EnumerationFormat < RecordList
712 class EnumerationFormat < RecordList
713 add 'enumeration'
713 add 'enumeration'
714 self.form_partial = 'custom_fields/formats/enumeration'
714 self.form_partial = 'custom_fields/formats/enumeration'
715
715
716 def label
716 def label
717 "label_field_format_enumeration"
717 "label_field_format_enumeration"
718 end
718 end
719
719
720 def target_class
720 def target_class
721 @target_class ||= CustomFieldEnumeration
721 @target_class ||= CustomFieldEnumeration
722 end
722 end
723
723
724 def possible_values_options(custom_field, object=nil)
724 def possible_values_options(custom_field, object=nil)
725 possible_values_records(custom_field, object).map {|u| [u.name, u.id.to_s]}
725 possible_values_records(custom_field, object).map {|u| [u.name, u.id.to_s]}
726 end
726 end
727
727
728 def possible_values_records(custom_field, object=nil)
728 def possible_values_records(custom_field, object=nil)
729 custom_field.enumerations.active
729 custom_field.enumerations.active
730 end
730 end
731
731
732 def value_from_keyword(custom_field, keyword, object)
732 def value_from_keyword(custom_field, keyword, object)
733 value = custom_field.enumerations.where("LOWER(name) LIKE LOWER(?)", keyword).first
733 value = custom_field.enumerations.where("LOWER(name) LIKE LOWER(?)", keyword).first
734 value ? value.id : nil
734 value ? value.id : nil
735 end
735 end
736 end
736 end
737
737
738 class UserFormat < RecordList
738 class UserFormat < RecordList
739 add 'user'
739 add 'user'
740 self.form_partial = 'custom_fields/formats/user'
740 self.form_partial = 'custom_fields/formats/user'
741 field_attributes :user_role
741 field_attributes :user_role
742
742
743 def possible_values_options(custom_field, object=nil)
743 def possible_values_options(custom_field, object=nil)
744 possible_values_records(custom_field, object).map {|u| [u.name, u.id.to_s]}
744 possible_values_records(custom_field, object).map {|u| [u.name, u.id.to_s]}
745 end
745 end
746
746
747 def possible_values_records(custom_field, object=nil)
747 def possible_values_records(custom_field, object=nil)
748 if object.is_a?(Array)
748 if object.is_a?(Array)
749 projects = object.map {|o| o.respond_to?(:project) ? o.project : nil}.compact.uniq
749 projects = object.map {|o| o.respond_to?(:project) ? o.project : nil}.compact.uniq
750 projects.map {|project| possible_values_records(custom_field, project)}.reduce(:&) || []
750 projects.map {|project| possible_values_records(custom_field, project)}.reduce(:&) || []
751 elsif object.respond_to?(:project) && object.project
751 elsif object.respond_to?(:project) && object.project
752 scope = object.project.users
752 scope = object.project.users
753 if custom_field.user_role.is_a?(Array)
753 if custom_field.user_role.is_a?(Array)
754 role_ids = custom_field.user_role.map(&:to_s).reject(&:blank?).map(&:to_i)
754 role_ids = custom_field.user_role.map(&:to_s).reject(&:blank?).map(&:to_i)
755 if role_ids.any?
755 if role_ids.any?
756 scope = scope.where("#{Member.table_name}.id IN (SELECT DISTINCT member_id FROM #{MemberRole.table_name} WHERE role_id IN (?))", role_ids)
756 scope = scope.where("#{Member.table_name}.id IN (SELECT DISTINCT member_id FROM #{MemberRole.table_name} WHERE role_id IN (?))", role_ids)
757 end
757 end
758 end
758 end
759 scope.sorted
759 scope.sorted
760 else
760 else
761 []
761 []
762 end
762 end
763 end
763 end
764
764
765 def value_from_keyword(custom_field, keyword, object)
765 def value_from_keyword(custom_field, keyword, object)
766 users = possible_values_records(custom_field, object).to_a
766 users = possible_values_records(custom_field, object).to_a
767 user = Principal.detect_by_keyword(users, keyword)
767 user = Principal.detect_by_keyword(users, keyword)
768 user ? user.id : nil
768 user ? user.id : nil
769 end
769 end
770
770
771 def before_custom_field_save(custom_field)
771 def before_custom_field_save(custom_field)
772 super
772 super
773 if custom_field.user_role.is_a?(Array)
773 if custom_field.user_role.is_a?(Array)
774 custom_field.user_role.map!(&:to_s).reject!(&:blank?)
774 custom_field.user_role.map!(&:to_s).reject!(&:blank?)
775 end
775 end
776 end
776 end
777 end
777 end
778
778
779 class VersionFormat < RecordList
779 class VersionFormat < RecordList
780 add 'version'
780 add 'version'
781 self.form_partial = 'custom_fields/formats/version'
781 self.form_partial = 'custom_fields/formats/version'
782 field_attributes :version_status
782 field_attributes :version_status
783
783
784 def possible_values_options(custom_field, object=nil)
784 def possible_values_options(custom_field, object=nil)
785 versions_options(custom_field, object)
785 versions_options(custom_field, object)
786 end
786 end
787
787
788 def before_custom_field_save(custom_field)
788 def before_custom_field_save(custom_field)
789 super
789 super
790 if custom_field.version_status.is_a?(Array)
790 if custom_field.version_status.is_a?(Array)
791 custom_field.version_status.map!(&:to_s).reject!(&:blank?)
791 custom_field.version_status.map!(&:to_s).reject!(&:blank?)
792 end
792 end
793 end
793 end
794
794
795 protected
795 protected
796
796
797 def query_filter_values(custom_field, query)
797 def query_filter_values(custom_field, query)
798 versions_options(custom_field, query.project, true)
798 versions_options(custom_field, query.project, true)
799 end
799 end
800
800
801 def versions_options(custom_field, object, all_statuses=false)
801 def versions_options(custom_field, object, all_statuses=false)
802 if object.is_a?(Array)
802 if object.is_a?(Array)
803 projects = object.map {|o| o.respond_to?(:project) ? o.project : nil}.compact.uniq
803 projects = object.map {|o| o.respond_to?(:project) ? o.project : nil}.compact.uniq
804 projects.map {|project| possible_values_options(custom_field, project)}.reduce(:&) || []
804 projects.map {|project| possible_values_options(custom_field, project)}.reduce(:&) || []
805 elsif object.respond_to?(:project) && object.project
805 elsif object.respond_to?(:project) && object.project
806 scope = object.project.shared_versions
806 scope = object.project.shared_versions
807 if !all_statuses && custom_field.version_status.is_a?(Array)
807 filtered_versions_options(custom_field, scope, all_statuses)
808 statuses = custom_field.version_status.map(&:to_s).reject(&:blank?)
808 elsif object.nil?
809 if statuses.any?
809 scope = Version.visible.where(:sharing => 'system')
810 scope = scope.where(:status => statuses.map(&:to_s))
810 filtered_versions_options(custom_field, scope, all_statuses)
811 end
812 end
813 scope.sort.collect {|u| [u.to_s, u.id.to_s]}
814 else
811 else
815 []
812 []
816 end
813 end
817 end
814 end
815
816 def filtered_versions_options(custom_field, scope, all_statuses=false)
817 if !all_statuses && custom_field.version_status.is_a?(Array)
818 statuses = custom_field.version_status.map(&:to_s).reject(&:blank?)
819 if statuses.any?
820 scope = scope.where(:status => statuses.map(&:to_s))
821 end
822 end
823 scope.sort.collect{|u| [u.to_s, u.id.to_s] }
824 end
818 end
825 end
819 end
826 end
820 end
827 end
@@ -1,60 +1,61
1 # Redmine - project management software
1 # Redmine - project management software
2 # Copyright (C) 2006-2016 Jean-Philippe Lang
2 # Copyright (C) 2006-2016 Jean-Philippe Lang
3 #
3 #
4 # This program is free software; you can redistribute it and/or
4 # This program is free software; you can redistribute it and/or
5 # modify it under the terms of the GNU General Public License
5 # modify it under the terms of the GNU General Public License
6 # as published by the Free Software Foundation; either version 2
6 # as published by the Free Software Foundation; either version 2
7 # of the License, or (at your option) any later version.
7 # of the License, or (at your option) any later version.
8 #
8 #
9 # This program is distributed in the hope that it will be useful,
9 # This program is distributed in the hope that it will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 # GNU General Public License for more details.
12 # GNU General Public License for more details.
13 #
13 #
14 # You should have received a copy of the GNU General Public License
14 # You should have received a copy of the GNU General Public License
15 # along with this program; if not, write to the Free Software
15 # along with this program; if not, write to the Free Software
16 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
16 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17
17
18 require File.expand_path('../../test_helper', __FILE__)
18 require File.expand_path('../../test_helper', __FILE__)
19
19
20 class CustomFieldVersionFormatTest < ActiveSupport::TestCase
20 class CustomFieldVersionFormatTest < ActiveSupport::TestCase
21 fixtures :custom_fields, :projects, :members, :users, :member_roles, :trackers, :issues, :versions
21 fixtures :custom_fields, :projects, :members, :users, :member_roles, :trackers, :issues, :versions
22
22
23 def setup
23 def setup
24 @field = IssueCustomField.create!(:name => 'Tester', :field_format => 'version')
24 @field = IssueCustomField.create!(:name => 'Tester', :field_format => 'version')
25 end
25 end
26
26
27 def test_possible_values_options_with_no_arguments
27 def test_possible_values_options_with_no_arguments
28 Version.delete_all
28 assert_equal [], @field.possible_values_options
29 assert_equal [], @field.possible_values_options
29 assert_equal [], @field.possible_values_options(nil)
30 assert_equal [], @field.possible_values_options(nil)
30 end
31 end
31
32
32 def test_possible_values_options_with_project_resource
33 def test_possible_values_options_with_project_resource
33 project = Project.find(1)
34 project = Project.find(1)
34 possible_values_options = @field.possible_values_options(project.issues.first)
35 possible_values_options = @field.possible_values_options(project.issues.first)
35 assert possible_values_options.any?
36 assert possible_values_options.any?
36 assert_equal project.shared_versions.sort.map {|u| [u.name, u.id.to_s]}, possible_values_options
37 assert_equal project.shared_versions.sort.map {|u| [u.name, u.id.to_s]}, possible_values_options
37 end
38 end
38
39
39 def test_possible_values_options_with_array
40 def test_possible_values_options_with_array
40 projects = Project.find([1, 2])
41 projects = Project.find([1, 2])
41 possible_values_options = @field.possible_values_options(projects)
42 possible_values_options = @field.possible_values_options(projects)
42 assert possible_values_options.any?
43 assert possible_values_options.any?
43 assert_equal (projects.first.shared_versions & projects.last.shared_versions).sort.map {|u| [u.name, u.id.to_s]}, possible_values_options
44 assert_equal (projects.first.shared_versions & projects.last.shared_versions).sort.map {|u| [u.name, u.id.to_s]}, possible_values_options
44 end
45 end
45
46
46 def test_cast_blank_value
47 def test_cast_blank_value
47 assert_equal nil, @field.cast_value(nil)
48 assert_equal nil, @field.cast_value(nil)
48 assert_equal nil, @field.cast_value("")
49 assert_equal nil, @field.cast_value("")
49 end
50 end
50
51
51 def test_cast_valid_value
52 def test_cast_valid_value
52 version = @field.cast_value("2")
53 version = @field.cast_value("2")
53 assert_kind_of Version, version
54 assert_kind_of Version, version
54 assert_equal Version.find(2), version
55 assert_equal Version.find(2), version
55 end
56 end
56
57
57 def test_cast_invalid_value
58 def test_cast_invalid_value
58 assert_equal nil, @field.cast_value("187")
59 assert_equal nil, @field.cast_value("187")
59 end
60 end
60 end
61 end
@@ -1,79 +1,88
1 # Redmine - project management software
1 # Redmine - project management software
2 # Copyright (C) 2006-2016 Jean-Philippe Lang
2 # Copyright (C) 2006-2016 Jean-Philippe Lang
3 #
3 #
4 # This program is free software; you can redistribute it and/or
4 # This program is free software; you can redistribute it and/or
5 # modify it under the terms of the GNU General Public License
5 # modify it under the terms of the GNU General Public License
6 # as published by the Free Software Foundation; either version 2
6 # as published by the Free Software Foundation; either version 2
7 # of the License, or (at your option) any later version.
7 # of the License, or (at your option) any later version.
8 #
8 #
9 # This program is distributed in the hope that it will be useful,
9 # This program is distributed in the hope that it will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 # GNU General Public License for more details.
12 # GNU General Public License for more details.
13 #
13 #
14 # You should have received a copy of the GNU General Public License
14 # You should have received a copy of the GNU General Public License
15 # along with this program; if not, write to the Free Software
15 # along with this program; if not, write to the Free Software
16 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
16 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17
17
18 require File.expand_path('../../../../../test_helper', __FILE__)
18 require File.expand_path('../../../../../test_helper', __FILE__)
19 require 'redmine/field_format'
19 require 'redmine/field_format'
20
20
21 class Redmine::VersionFieldFormatTest < ActionView::TestCase
21 class Redmine::VersionFieldFormatTest < ActionView::TestCase
22 fixtures :projects, :versions, :trackers,
22 fixtures :projects, :versions, :trackers,
23 :roles, :users, :members, :member_roles,
23 :roles, :users, :members, :member_roles,
24 :issue_statuses, :issue_categories, :issue_relations, :workflows,
24 :issue_statuses, :issue_categories, :issue_relations, :workflows,
25 :enumerations
25 :enumerations
26
26
27 def test_version_status_should_reject_blank_values
27 def test_version_status_should_reject_blank_values
28 field = IssueCustomField.new(:name => 'Foo', :field_format => 'version', :version_status => ["open", ""])
28 field = IssueCustomField.new(:name => 'Foo', :field_format => 'version', :version_status => ["open", ""])
29 field.save!
29 field.save!
30 assert_equal ["open"], field.version_status
30 assert_equal ["open"], field.version_status
31 end
31 end
32
32
33 def test_existing_values_should_be_valid
33 def test_existing_values_should_be_valid
34 field = IssueCustomField.create!(:name => 'Foo', :field_format => 'version', :is_for_all => true, :trackers => Tracker.all)
34 field = IssueCustomField.create!(:name => 'Foo', :field_format => 'version', :is_for_all => true, :trackers => Tracker.all)
35 project = Project.generate!
35 project = Project.generate!
36 version = Version.generate!(:project => project, :status => 'open')
36 version = Version.generate!(:project => project, :status => 'open')
37 issue = Issue.generate!(:project_id => project.id, :tracker_id => 1, :custom_field_values => {field.id => version.id})
37 issue = Issue.generate!(:project_id => project.id, :tracker_id => 1, :custom_field_values => {field.id => version.id})
38
38
39 field.version_status = ["open"]
39 field.version_status = ["open"]
40 field.save!
40 field.save!
41
41
42 issue = Issue.order('id DESC').first
42 issue = Issue.order('id DESC').first
43 assert_include [version.name, version.id.to_s], field.possible_custom_value_options(issue.custom_value_for(field))
43 assert_include [version.name, version.id.to_s], field.possible_custom_value_options(issue.custom_value_for(field))
44 assert issue.valid?
44 assert issue.valid?
45 end
45 end
46
46
47 def test_possible_values_options_should_return_project_versions
47 def test_possible_values_options_should_return_project_versions
48 field = IssueCustomField.new(:field_format => 'version')
48 field = IssueCustomField.new(:field_format => 'version')
49 project = Project.find(1)
49 project = Project.find(1)
50 expected = project.shared_versions.sort.map(&:name)
50 expected = project.shared_versions.sort.map(&:name)
51
51
52 assert_equal expected, field.possible_values_options(project).map(&:first)
52 assert_equal expected, field.possible_values_options(project).map(&:first)
53 end
53 end
54
55 def test_possible_values_options_should_return_system_shared_versions_without_project
56 field = IssueCustomField.new(:field_format => 'version')
57 version = Version.generate!(:project => Project.find(1), :status => 'open', :sharing => 'system')
58
59 expected = Version.visible.where(:sharing => 'system').sort.map(&:name)
60 assert_include version.name, expected
61 assert_equal expected, field.possible_values_options.map(&:first)
62 end
54
63
55 def test_possible_values_options_should_return_project_versions_with_selected_status
64 def test_possible_values_options_should_return_project_versions_with_selected_status
56 field = IssueCustomField.new(:field_format => 'version', :version_status => ["open"])
65 field = IssueCustomField.new(:field_format => 'version', :version_status => ["open"])
57 project = Project.find(1)
66 project = Project.find(1)
58 expected = project.shared_versions.sort.select {|v| v.status == "open"}.map(&:name)
67 expected = project.shared_versions.sort.select {|v| v.status == "open"}.map(&:name)
59
68
60 assert_equal expected, field.possible_values_options(project).map(&:first)
69 assert_equal expected, field.possible_values_options(project).map(&:first)
61 end
70 end
62
71
63 def test_cast_value_should_not_raise_error_when_array_contains_value_casted_to_nil
72 def test_cast_value_should_not_raise_error_when_array_contains_value_casted_to_nil
64 field = IssueCustomField.new(:field_format => 'version')
73 field = IssueCustomField.new(:field_format => 'version')
65 assert_nothing_raised do
74 assert_nothing_raised do
66 field.cast_value([1,2, 42])
75 field.cast_value([1,2, 42])
67 end
76 end
68 end
77 end
69
78
70 def test_query_filter_options_should_include_versions_with_any_status
79 def test_query_filter_options_should_include_versions_with_any_status
71 field = IssueCustomField.new(:field_format => 'version', :version_status => ["open"])
80 field = IssueCustomField.new(:field_format => 'version', :version_status => ["open"])
72 project = Project.find(1)
81 project = Project.find(1)
73 version = Version.generate!(:project => project, :status => 'locked')
82 version = Version.generate!(:project => project, :status => 'locked')
74 query = Query.new(:project => project)
83 query = Query.new(:project => project)
75
84
76 assert_not_include version.name, field.possible_values_options(project).map(&:first)
85 assert_not_include version.name, field.possible_values_options(project).map(&:first)
77 assert_include version.name, field.query_filter_options(query)[:values].map(&:first)
86 assert_include version.name, field.query_filter_options(query)[:values].map(&:first)
78 end
87 end
79 end
88 end
General Comments 0
You need to be logged in to leave comments. Login now