You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

custom_field.rb 13KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355
  1. # Redmine - project management software
  2. # Copyright (C) 2006-2013 Jean-Philippe Lang
  3. #
  4. # This program is free software; you can redistribute it and/or
  5. # modify it under the terms of the GNU General Public License
  6. # as published by the Free Software Foundation; either version 2
  7. # of the License, or (at your option) any later version.
  8. #
  9. # This program is distributed in the hope that it will be useful,
  10. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. # GNU General Public License for more details.
  13. #
  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
  16. # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
  17. class CustomField < ActiveRecord::Base
  18. include Redmine::SubclassFactory
  19. has_many :custom_values, :dependent => :delete_all
  20. acts_as_list :scope => 'type = \'#{self.class}\''
  21. serialize :possible_values
  22. validates_presence_of :name, :field_format
  23. validates_uniqueness_of :name, :scope => :type
  24. validates_length_of :name, :maximum => 30
  25. validates_inclusion_of :field_format, :in => Redmine::CustomFieldFormat.available_formats
  26. validate :validate_custom_field
  27. before_validation :set_searchable
  28. after_save :handle_multiplicity_change
  29. scope :sorted, lambda { order("#{table_name}.position ASC") }
  30. CUSTOM_FIELDS_TABS = [
  31. {:name => 'IssueCustomField', :partial => 'custom_fields/index',
  32. :label => :label_issue_plural},
  33. {:name => 'TimeEntryCustomField', :partial => 'custom_fields/index',
  34. :label => :label_spent_time},
  35. {:name => 'ProjectCustomField', :partial => 'custom_fields/index',
  36. :label => :label_project_plural},
  37. {:name => 'VersionCustomField', :partial => 'custom_fields/index',
  38. :label => :label_version_plural},
  39. {:name => 'UserCustomField', :partial => 'custom_fields/index',
  40. :label => :label_user_plural},
  41. {:name => 'GroupCustomField', :partial => 'custom_fields/index',
  42. :label => :label_group_plural},
  43. {:name => 'TimeEntryActivityCustomField', :partial => 'custom_fields/index',
  44. :label => TimeEntryActivity::OptionName},
  45. {:name => 'IssuePriorityCustomField', :partial => 'custom_fields/index',
  46. :label => IssuePriority::OptionName},
  47. {:name => 'DocumentCategoryCustomField', :partial => 'custom_fields/index',
  48. :label => DocumentCategory::OptionName}
  49. ]
  50. CUSTOM_FIELDS_NAMES = CUSTOM_FIELDS_TABS.collect{|v| v[:name]}
  51. def field_format=(arg)
  52. # cannot change format of a saved custom field
  53. super if new_record?
  54. end
  55. def set_searchable
  56. # make sure these fields are not searchable
  57. self.searchable = false if %w(int float date bool).include?(field_format)
  58. # make sure only these fields can have multiple values
  59. self.multiple = false unless %w(list user version).include?(field_format)
  60. true
  61. end
  62. def validate_custom_field
  63. if self.field_format == "list"
  64. errors.add(:possible_values, :blank) if self.possible_values.nil? || self.possible_values.empty?
  65. errors.add(:possible_values, :invalid) unless self.possible_values.is_a? Array
  66. end
  67. if regexp.present?
  68. begin
  69. Regexp.new(regexp)
  70. rescue
  71. errors.add(:regexp, :invalid)
  72. end
  73. end
  74. if default_value.present? && !valid_field_value?(default_value)
  75. errors.add(:default_value, :invalid)
  76. end
  77. end
  78. def possible_values_options(obj=nil)
  79. case field_format
  80. when 'user', 'version'
  81. if obj.respond_to?(:project) && obj.project
  82. case field_format
  83. when 'user'
  84. obj.project.users.sort.collect {|u| [u.to_s, u.id.to_s]}
  85. when 'version'
  86. obj.project.shared_versions.sort.collect {|u| [u.to_s, u.id.to_s]}
  87. end
  88. elsif obj.is_a?(Array)
  89. obj.collect {|o| possible_values_options(o)}.reduce(:&)
  90. else
  91. []
  92. end
  93. when 'bool'
  94. [[l(:general_text_Yes), '1'], [l(:general_text_No), '0']]
  95. else
  96. possible_values || []
  97. end
  98. end
  99. def possible_values(obj=nil)
  100. case field_format
  101. when 'user', 'version'
  102. possible_values_options(obj).collect(&:last)
  103. when 'bool'
  104. ['1', '0']
  105. else
  106. values = super()
  107. if values.is_a?(Array)
  108. values.each do |value|
  109. value.force_encoding('UTF-8') if value.respond_to?(:force_encoding)
  110. end
  111. end
  112. values || []
  113. end
  114. end
  115. # Makes possible_values accept a multiline string
  116. def possible_values=(arg)
  117. if arg.is_a?(Array)
  118. super(arg.compact.collect(&:strip).select {|v| !v.blank?})
  119. else
  120. self.possible_values = arg.to_s.split(/[\n\r]+/)
  121. end
  122. end
  123. def cast_value(value)
  124. casted = nil
  125. unless value.blank?
  126. case field_format
  127. when 'string', 'text', 'list'
  128. casted = value
  129. when 'date'
  130. casted = begin; value.to_date; rescue; nil end
  131. when 'bool'
  132. casted = (value == '1' ? true : false)
  133. when 'int'
  134. casted = value.to_i
  135. when 'float'
  136. casted = value.to_f
  137. when 'user', 'version'
  138. casted = (value.blank? ? nil : field_format.classify.constantize.find_by_id(value.to_i))
  139. end
  140. end
  141. casted
  142. end
  143. def value_from_keyword(keyword, customized)
  144. possible_values_options = possible_values_options(customized)
  145. if possible_values_options.present?
  146. keyword = keyword.to_s.downcase
  147. if v = possible_values_options.detect {|text, id| text.downcase == keyword}
  148. if v.is_a?(Array)
  149. v.last
  150. else
  151. v
  152. end
  153. end
  154. else
  155. keyword
  156. end
  157. end
  158. # Returns a ORDER BY clause that can used to sort customized
  159. # objects by their value of the custom field.
  160. # Returns nil if the custom field can not be used for sorting.
  161. def order_statement
  162. return nil if multiple?
  163. case field_format
  164. when 'string', 'text', 'list', 'date', 'bool'
  165. # COALESCE is here to make sure that blank and NULL values are sorted equally
  166. "COALESCE(#{join_alias}.value, '')"
  167. when 'int', 'float'
  168. # Make the database cast values into numeric
  169. # Postgresql will raise an error if a value can not be casted!
  170. # CustomValue validations should ensure that it doesn't occur
  171. "CAST(CASE #{join_alias}.value WHEN '' THEN '0' ELSE #{join_alias}.value END AS decimal(30,3))"
  172. when 'user', 'version'
  173. value_class.fields_for_order_statement(value_join_alias)
  174. else
  175. nil
  176. end
  177. end
  178. # Returns a GROUP BY clause that can used to group by custom value
  179. # Returns nil if the custom field can not be used for grouping.
  180. def group_statement
  181. return nil if multiple?
  182. case field_format
  183. when 'list', 'date', 'bool', 'int'
  184. order_statement
  185. when 'user', 'version'
  186. "COALESCE(#{join_alias}.value, '')"
  187. else
  188. nil
  189. end
  190. end
  191. def join_for_order_statement
  192. case field_format
  193. when 'user', 'version'
  194. "LEFT OUTER JOIN #{CustomValue.table_name} #{join_alias}" +
  195. " ON #{join_alias}.customized_type = '#{self.class.customized_class.base_class.name}'" +
  196. " AND #{join_alias}.customized_id = #{self.class.customized_class.table_name}.id" +
  197. " AND #{join_alias}.custom_field_id = #{id}" +
  198. " AND #{join_alias}.value <> ''" +
  199. " AND #{join_alias}.id = (SELECT max(#{join_alias}_2.id) FROM #{CustomValue.table_name} #{join_alias}_2" +
  200. " WHERE #{join_alias}_2.customized_type = #{join_alias}.customized_type" +
  201. " AND #{join_alias}_2.customized_id = #{join_alias}.customized_id" +
  202. " AND #{join_alias}_2.custom_field_id = #{join_alias}.custom_field_id)" +
  203. " LEFT OUTER JOIN #{value_class.table_name} #{value_join_alias}" +
  204. " ON CAST(CASE #{join_alias}.value WHEN '' THEN '0' ELSE #{join_alias}.value END AS decimal(30,0)) = #{value_join_alias}.id"
  205. when 'int', 'float'
  206. "LEFT OUTER JOIN #{CustomValue.table_name} #{join_alias}" +
  207. " ON #{join_alias}.customized_type = '#{self.class.customized_class.base_class.name}'" +
  208. " AND #{join_alias}.customized_id = #{self.class.customized_class.table_name}.id" +
  209. " AND #{join_alias}.custom_field_id = #{id}" +
  210. " AND #{join_alias}.value <> ''" +
  211. " AND #{join_alias}.id = (SELECT max(#{join_alias}_2.id) FROM #{CustomValue.table_name} #{join_alias}_2" +
  212. " WHERE #{join_alias}_2.customized_type = #{join_alias}.customized_type" +
  213. " AND #{join_alias}_2.customized_id = #{join_alias}.customized_id" +
  214. " AND #{join_alias}_2.custom_field_id = #{join_alias}.custom_field_id)"
  215. when 'string', 'text', 'list', 'date', 'bool'
  216. "LEFT OUTER JOIN #{CustomValue.table_name} #{join_alias}" +
  217. " ON #{join_alias}.customized_type = '#{self.class.customized_class.base_class.name}'" +
  218. " AND #{join_alias}.customized_id = #{self.class.customized_class.table_name}.id" +
  219. " AND #{join_alias}.custom_field_id = #{id}" +
  220. " AND #{join_alias}.id = (SELECT max(#{join_alias}_2.id) FROM #{CustomValue.table_name} #{join_alias}_2" +
  221. " WHERE #{join_alias}_2.customized_type = #{join_alias}.customized_type" +
  222. " AND #{join_alias}_2.customized_id = #{join_alias}.customized_id" +
  223. " AND #{join_alias}_2.custom_field_id = #{join_alias}.custom_field_id)"
  224. else
  225. nil
  226. end
  227. end
  228. def join_alias
  229. "cf_#{id}"
  230. end
  231. def value_join_alias
  232. join_alias + "_" + field_format
  233. end
  234. def <=>(field)
  235. position <=> field.position
  236. end
  237. # Returns the class that values represent
  238. def value_class
  239. case field_format
  240. when 'user', 'version'
  241. field_format.classify.constantize
  242. else
  243. nil
  244. end
  245. end
  246. def self.customized_class
  247. self.name =~ /^(.+)CustomField$/
  248. begin; $1.constantize; rescue nil; end
  249. end
  250. # to move in project_custom_field
  251. def self.for_all
  252. where(:is_for_all => true).order('position').all
  253. end
  254. def type_name
  255. nil
  256. end
  257. # Returns the error messages for the given value
  258. # or an empty array if value is a valid value for the custom field
  259. def validate_field_value(value)
  260. errs = []
  261. if value.is_a?(Array)
  262. if !multiple?
  263. errs << ::I18n.t('activerecord.errors.messages.invalid')
  264. end
  265. if is_required? && value.detect(&:present?).nil?
  266. errs << ::I18n.t('activerecord.errors.messages.blank')
  267. end
  268. value.each {|v| errs += validate_field_value_format(v)}
  269. else
  270. if is_required? && value.blank?
  271. errs << ::I18n.t('activerecord.errors.messages.blank')
  272. end
  273. errs += validate_field_value_format(value)
  274. end
  275. errs
  276. end
  277. # Returns true if value is a valid value for the custom field
  278. def valid_field_value?(value)
  279. validate_field_value(value).empty?
  280. end
  281. def format_in?(*args)
  282. args.include?(field_format)
  283. end
  284. protected
  285. # Returns the error message for the given value regarding its format
  286. def validate_field_value_format(value)
  287. errs = []
  288. if value.present?
  289. errs << ::I18n.t('activerecord.errors.messages.invalid') unless regexp.blank? or value =~ Regexp.new(regexp)
  290. errs << ::I18n.t('activerecord.errors.messages.too_short', :count => min_length) if min_length > 0 and value.length < min_length
  291. errs << ::I18n.t('activerecord.errors.messages.too_long', :count => max_length) if max_length > 0 and value.length > max_length
  292. # Format specific validations
  293. case field_format
  294. when 'int'
  295. errs << ::I18n.t('activerecord.errors.messages.not_a_number') unless value =~ /^[+-]?\d+$/
  296. when 'float'
  297. begin; Kernel.Float(value); rescue; errs << ::I18n.t('activerecord.errors.messages.invalid') end
  298. when 'date'
  299. errs << ::I18n.t('activerecord.errors.messages.not_a_date') unless value =~ /^\d{4}-\d{2}-\d{2}$/ && begin; value.to_date; rescue; false end
  300. when 'list'
  301. errs << ::I18n.t('activerecord.errors.messages.inclusion') unless possible_values.include?(value)
  302. end
  303. end
  304. errs
  305. end
  306. # Removes multiple values for the custom field after setting the multiple attribute to false
  307. # We kepp the value with the highest id for each customized object
  308. def handle_multiplicity_change
  309. if !new_record? && multiple_was && !multiple
  310. ids = custom_values.
  311. where("EXISTS(SELECT 1 FROM #{CustomValue.table_name} cve WHERE cve.custom_field_id = #{CustomValue.table_name}.custom_field_id" +
  312. " AND cve.customized_type = #{CustomValue.table_name}.customized_type AND cve.customized_id = #{CustomValue.table_name}.customized_id" +
  313. " AND cve.id > #{CustomValue.table_name}.id)").
  314. pluck(:id)
  315. if ids.any?
  316. custom_values.where(:id => ids).delete_all
  317. end
  318. end
  319. end
  320. end