From 2e2e2cfe425c2664517fb59836fbd3eff5e35861 Mon Sep 17 00:00:00 2001 From: Jean-Philippe Lang Date: Sat, 14 Dec 2013 08:22:43 +0000 Subject: [PATCH] Merged custom fields format refactoring. git-svn-id: http://svn.redmine.org/redmine/trunk@12400 e93f8b46-1217-0410-a6f0-8f06a7374b81 --- app/controllers/custom_fields_controller.rb | 4 +- app/helpers/application_helper.rb | 15 +- app/helpers/custom_fields_helper.rb | 131 ++-- app/helpers/issues_helper.rb | 9 +- app/helpers/timelog_helper.rb | 4 +- app/models/custom_field.rb | 212 ++---- app/models/custom_field_value.rb | 10 +- app/models/query.rb | 29 +- app/views/custom_fields/_form.html.erb | 71 +- app/views/custom_fields/_index.html.erb | 2 +- .../custom_fields/formats/_bool.html.erb | 2 + .../custom_fields/formats/_date.html.erb | 2 + .../custom_fields/formats/_link.html.erb | 3 + .../custom_fields/formats/_list.html.erb | 6 + .../custom_fields/formats/_numeric.html.erb | 2 + .../custom_fields/formats/_regexp.html.erb | 10 + .../custom_fields/formats/_string.html.erb | 3 + .../custom_fields/formats/_text.html.erb | 3 + .../custom_fields/formats/_user.html.erb | 24 + .../custom_fields/formats/_version.html.erb | 24 + app/views/custom_fields/new.html.erb | 3 +- app/views/issues/bulk_edit.html.erb | 2 +- app/views/timelog/bulk_edit.html.erb | 2 +- ...24175346_add_custom_fields_format_store.rb | 9 + ...210180802_add_custom_fields_description.rb | 9 + .../lib/acts_as_customizable.rb | 1 + lib/redmine.rb | 13 - lib/redmine/custom_field_format.rb | 115 ---- lib/redmine/export/pdf.rb | 4 +- lib/redmine/field_format.rb | 646 ++++++++++++++++++ lib/redmine/helpers/time_report.rb | 3 +- lib/redmine/views/labelled_form_builder.rb | 6 +- public/javascripts/application.js | 14 + public/stylesheets/application.css | 33 +- .../custom_fields_controller_test.rb | 29 +- test/functional/issues_controller_test.rb | 6 +- test/unit/custom_field_test.rb | 18 +- test/unit/custom_field_user_format_test.rb | 17 - test/unit/custom_field_version_format_test.rb | 16 - .../unit/helpers/custom_fields_helper_test.rb | 5 +- .../redmine/field_format/field_format_test.rb | 55 ++ .../redmine/field_format/link_format_test.rb | 79 +++ .../redmine/field_format/list_format_test.rb | 135 ++++ .../field_format/user_field_format_test.rb | 60 ++ .../field_format/version_field_format_test.rb | 61 ++ 45 files changed, 1388 insertions(+), 519 deletions(-) create mode 100644 app/views/custom_fields/formats/_bool.html.erb create mode 100644 app/views/custom_fields/formats/_date.html.erb create mode 100644 app/views/custom_fields/formats/_link.html.erb create mode 100644 app/views/custom_fields/formats/_list.html.erb create mode 100644 app/views/custom_fields/formats/_numeric.html.erb create mode 100644 app/views/custom_fields/formats/_regexp.html.erb create mode 100644 app/views/custom_fields/formats/_string.html.erb create mode 100644 app/views/custom_fields/formats/_text.html.erb create mode 100644 app/views/custom_fields/formats/_user.html.erb create mode 100644 app/views/custom_fields/formats/_version.html.erb create mode 100644 db/migrate/20131124175346_add_custom_fields_format_store.rb create mode 100644 db/migrate/20131210180802_add_custom_fields_description.rb delete mode 100644 lib/redmine/custom_field_format.rb create mode 100644 lib/redmine/field_format.rb create mode 100644 test/unit/lib/redmine/field_format/field_format_test.rb create mode 100644 test/unit/lib/redmine/field_format/link_format_test.rb create mode 100644 test/unit/lib/redmine/field_format/list_format_test.rb create mode 100644 test/unit/lib/redmine/field_format/user_field_format_test.rb create mode 100644 test/unit/lib/redmine/field_format/version_field_format_test.rb diff --git a/app/controllers/custom_fields_controller.rb b/app/controllers/custom_fields_controller.rb index 95d0d507f..6fd9cd58c 100644 --- a/app/controllers/custom_fields_controller.rb +++ b/app/controllers/custom_fields_controller.rb @@ -36,6 +36,8 @@ class CustomFieldsController < ApplicationController end def new + @custom_field.field_format = 'string' if @custom_field.field_format.blank? + @custom_field.default_value = nil end def create @@ -76,8 +78,6 @@ class CustomFieldsController < ApplicationController @custom_field = CustomField.new_subclass_instance(params[:type], params[:custom_field]) if @custom_field.nil? render_404 - else - @custom_field.default_value = nil end end diff --git a/app/helpers/application_helper.rb b/app/helpers/application_helper.rb index 357a7e04c..b83691c08 100644 --- a/app/helpers/application_helper.rb +++ b/app/helpers/application_helper.rb @@ -158,6 +158,8 @@ module ApplicationHelper # Helper that formats object for html or text rendering def format_object(object, html=true) case object.class.name + when 'Array' + object.map {|o| format_object(o, html)}.join(', ').html_safe when 'Time' format_time(object) when 'Date' @@ -171,13 +173,24 @@ module ApplicationHelper when 'Project' html ? link_to_project(object) : object.to_s when 'Version' - html ? link_to(object.name, version_path(object)) : version.to_s + html ? link_to(object.name, version_path(object)) : object.to_s when 'TrueClass' l(:general_text_Yes) when 'FalseClass' l(:general_text_No) when 'Issue' object.visible? && html ? link_to_issue(object) : "##{object.id}" + when 'CustomValue', 'CustomFieldValue' + if object.custom_field + f = object.custom_field.format.formatted_custom_value(self, object, html) + if f.nil? || f.is_a?(String) + f + else + format_object(f, html) + end + else + object.value.to_s + end else html ? h(object) : object.to_s end diff --git a/app/helpers/custom_fields_helper.rb b/app/helpers/custom_fields_helper.rb index fd549f5ab..f62c36f68 100644 --- a/app/helpers/custom_fields_helper.rb +++ b/app/helpers/custom_fields_helper.rb @@ -44,51 +44,39 @@ module CustomFieldsHelper CUSTOM_FIELDS_TABS end - # Return custom field html tag corresponding to its format - def custom_field_tag(name, custom_value) - custom_field = custom_value.custom_field - field_name = "#{name}[custom_field_values][#{custom_field.id}]" - field_name << "[]" if custom_field.multiple? - field_id = "#{name}_custom_field_values_#{custom_field.id}" - - tag_options = {:id => field_id, :class => "#{custom_field.field_format}_cf"} - - field_format = Redmine::CustomFieldFormat.find_by_name(custom_field.field_format) - case field_format.try(:edit_as) - when "date" - text_field_tag(field_name, custom_value.value, tag_options.merge(:size => 10)) + - calendar_for(field_id) - when "text" - text_area_tag(field_name, custom_value.value, tag_options.merge(:rows => 3)) - when "bool" - hidden_field_tag(field_name, '0') + check_box_tag(field_name, '1', custom_value.true?, tag_options) - when "list" - blank_option = ''.html_safe - unless custom_field.multiple? - if custom_field.is_required? - unless custom_field.default_value.present? - blank_option = content_tag('option', "--- #{l(:actionview_instancetag_blank_option)} ---", :value => '') - end - else - blank_option = content_tag('option') - end - end - s = select_tag(field_name, blank_option + options_for_select(custom_field.possible_values_options(custom_value.customized), custom_value.value), - tag_options.merge(:multiple => custom_field.multiple?)) - if custom_field.multiple? - s << hidden_field_tag(field_name, '') - end - s - else - text_field_tag(field_name, custom_value.value, tag_options) + def render_custom_field_format_partial(form, custom_field) + partial = custom_field.format.form_partial + if partial + render :partial => custom_field.format.form_partial, :locals => {:f => form, :custom_field => custom_field} end end + def custom_field_tag_name(prefix, custom_field) + name = "#{prefix}[custom_field_values][#{custom_field.id}]" + name << "[]" if custom_field.multiple? + name + end + + def custom_field_tag_id(prefix, custom_field) + "#{prefix}_custom_field_values_#{custom_field.id}" + end + + # Return custom field html tag corresponding to its format + def custom_field_tag(prefix, custom_value) + custom_value.custom_field.format.edit_tag self, + custom_field_tag_id(prefix, custom_value.custom_field), + custom_field_tag_name(prefix, custom_value.custom_field), + custom_value, + :class => "#{custom_value.custom_field.field_format}_cf" + end + # Return custom field label tag def custom_field_label_tag(name, custom_value, options={}) required = options[:required] || custom_value.custom_field.is_required? + title = custom_value.custom_field.description.presence + content = content_tag 'span', custom_value.custom_field.name, :title => title - content_tag "label", h(custom_value.custom_field.name) + + content_tag "label", content + (required ? " *".html_safe : ""), :for => "#{name}_custom_field_values_#{custom_value.custom_field.id}" end @@ -98,65 +86,30 @@ module CustomFieldsHelper custom_field_label_tag(name, custom_value, options) + custom_field_tag(name, custom_value) end - def custom_field_tag_for_bulk_edit(name, custom_field, projects=nil, value='') - field_name = "#{name}[custom_field_values][#{custom_field.id}]" - field_name << "[]" if custom_field.multiple? - field_id = "#{name}_custom_field_values_#{custom_field.id}" - - tag_options = {:id => field_id, :class => "#{custom_field.field_format}_cf"} - - unset_tag = '' - unless custom_field.is_required? - unset_tag = content_tag('label', - check_box_tag(field_name, '__none__', (value == '__none__'), :id => nil, :data => {:disables => "##{field_id}"}) + l(:button_clear), - :class => 'inline' - ) - end - - field_format = Redmine::CustomFieldFormat.find_by_name(custom_field.field_format) - case field_format.try(:edit_as) - when "date" - text_field_tag(field_name, value, tag_options.merge(:size => 10)) + - calendar_for(field_id) + - unset_tag - when "text" - text_area_tag(field_name, value, tag_options.merge(:rows => 3)) + - '
'.html_safe + - unset_tag - when "bool" - select_tag(field_name, options_for_select([[l(:label_no_change_option), ''], - [l(:general_text_yes), '1'], - [l(:general_text_no), '0']], value), tag_options) - when "list" - options = [] - options << [l(:label_no_change_option), ''] unless custom_field.multiple? - options << [l(:label_none), '__none__'] unless custom_field.is_required? - options += custom_field.possible_values_options(projects) - select_tag(field_name, options_for_select(options, value), tag_options.merge(:multiple => custom_field.multiple?)) - else - text_field_tag(field_name, value, tag_options) + - unset_tag - end + # Returns the custom field tag for when bulk editing objects + def custom_field_tag_for_bulk_edit(prefix, custom_field, objects=nil, value='') + custom_field.format.bulk_edit_tag self, + custom_field_tag_id(prefix, custom_field), + custom_field_tag_name(prefix, custom_field), + custom_field, + objects, + value, + :class => "#{custom_field.field_format}_cf" end # Return a string used to display a custom value - def show_value(custom_value) - return "" unless custom_value - format_value(custom_value.value, custom_value.custom_field.field_format) + def show_value(custom_value, html=true) + format_object(custom_value, html) end # Return a string used to display a custom value - def format_value(value, field_format) - if value.is_a?(Array) - value.collect {|v| format_value(v, field_format)}.compact.sort.join(', ') - else - Redmine::CustomFieldFormat.format_value(value, field_format) - end + def format_value(value, custom_field) + format_object(custom_field.format.formatted_value(self, custom_field, value, false), false) end # Return an array of custom field formats which can be used in select_tag def custom_field_formats_for_select(custom_field) - Redmine::CustomFieldFormat.as_select(custom_field.class.customized_class.name) + Redmine::FieldFormat.as_select(custom_field.class.customized_class.name) end # Renders the custom_values in api views @@ -179,4 +132,8 @@ module CustomFieldsHelper end end unless custom_values.empty? end + + def edit_tag_style_tag(form) + form.select :edit_tag_style, [[l(:label_drop_down_list), ''], [l(:label_checkboxes), 'check_box']], :label => :label_display + end end diff --git a/app/helpers/issues_helper.rb b/app/helpers/issues_helper.rb index 614c2f90d..9e70f5119 100644 --- a/app/helpers/issues_helper.rb +++ b/app/helpers/issues_helper.rb @@ -171,8 +171,9 @@ module IssuesHelper s = "\n" n = 0 ordered_values.compact.each do |value| + css = "cf_#{value.custom_field.id}" s << "\n\n" if n > 0 && (n % 2) == 0 - s << "\t#{ h(value.custom_field.name) }:#{ simple_format_without_paragraph(h(show_value(value))) }\n" + s << "\t#{ h(value.custom_field.name) }:#{ h(show_value(value)) }\n" n += 1 end s << "\n" @@ -239,7 +240,7 @@ module IssuesHelper end end issue.visible_custom_field_values(user).each do |value| - items << "#{value.custom_field.name}: #{show_value(value)}" + items << "#{value.custom_field.name}: #{show_value(value, false)}" end items end @@ -324,8 +325,8 @@ module IssuesHelper if custom_field multiple = custom_field.multiple? label = custom_field.name - value = format_value(detail.value, custom_field.field_format) if detail.value - old_value = format_value(detail.old_value, custom_field.field_format) if detail.old_value + value = format_value(detail.value, custom_field) if detail.value + old_value = format_value(detail.old_value, custom_field) if detail.old_value end when 'attachment' label = l(:label_attachment) diff --git a/app/helpers/timelog_helper.rb b/app/helpers/timelog_helper.rb index cf5629f52..8ea09d8d5 100644 --- a/app/helpers/timelog_helper.rb +++ b/app/helpers/timelog_helper.rb @@ -96,8 +96,10 @@ module TimelogHelper else obj end + elsif cf = criteria_options[:custom_field] + format_value(value, cf) else - format_value(value, criteria_options[:format]) + value.to_s end end diff --git a/app/models/custom_field.rb b/app/models/custom_field.rb index 055516c38..b2c54d030 100644 --- a/app/models/custom_field.rb +++ b/app/models/custom_field.rb @@ -22,14 +22,18 @@ class CustomField < ActiveRecord::Base has_and_belongs_to_many :roles, :join_table => "#{table_name_prefix}custom_fields_roles#{table_name_suffix}", :foreign_key => "custom_field_id" acts_as_list :scope => 'type = \'#{self.class}\'' serialize :possible_values + store :format_store validates_presence_of :name, :field_format validates_uniqueness_of :name, :scope => :type validates_length_of :name, :maximum => 30 - validates_inclusion_of :field_format, :in => Proc.new { Redmine::CustomFieldFormat.available_formats } + validates_inclusion_of :field_format, :in => Proc.new { Redmine::FieldFormat.available_formats } validate :validate_custom_field before_validation :set_searchable + before_save do |field| + field.format.before_custom_field_save(field) + end after_save :handle_multiplicity_change after_save do |field| if field.visible_changed? && field.visible @@ -57,23 +61,29 @@ class CustomField < ActiveRecord::Base visible? || user.admin? end + def format + @format ||= Redmine::FieldFormat.find(field_format) + end + def field_format=(arg) # cannot change format of a saved custom field - super if new_record? + if new_record? + @format = nil + super + end end def set_searchable # make sure these fields are not searchable - self.searchable = false if %w(int float date bool).include?(field_format) + self.searchable = false unless format.class.searchable_supported # make sure only these fields can have multiple values - self.multiple = false unless %w(list user version).include?(field_format) + self.multiple = false unless format.class.multiple_supported true end def validate_custom_field - if self.field_format == "list" - errors.add(:possible_values, :blank) if self.possible_values.nil? || self.possible_values.empty? - errors.add(:possible_values, :invalid) unless self.possible_values.is_a? Array + format.validate_custom_field(self).each do |attribute, message| + errors.add attribute, message end if regexp.present? @@ -84,49 +94,34 @@ class CustomField < ActiveRecord::Base end end - if default_value.present? && !valid_field_value?(default_value) - errors.add(:default_value, :invalid) + if default_value.present? + validate_field_value(default_value).each do |message| + errors.add :default_value, message + end end end - def possible_values_options(obj=nil) - case field_format - when 'user', 'version' - if obj.respond_to?(:project) && obj.project - case field_format - when 'user' - obj.project.users.sort.collect {|u| [u.to_s, u.id.to_s]} - when 'version' - obj.project.shared_versions.sort.collect {|u| [u.to_s, u.id.to_s]} - end - elsif obj.is_a?(Array) - obj.collect {|o| possible_values_options(o)}.reduce(:&) - else - [] - end - when 'bool' - [[l(:general_text_Yes), '1'], [l(:general_text_No), '0']] + def possible_custom_value_options(custom_value) + format.possible_custom_value_options(custom_value) + end + + def possible_values_options(object=nil) + if object.is_a?(Array) + object.map {|o| format.possible_values_options(self, o)}.reduce(:&) || [] else - possible_values || [] + format.possible_values_options(self, object) || [] end end - def possible_values(obj=nil) - case field_format - when 'user', 'version' - possible_values_options(obj).collect(&:last) - when 'bool' - ['1', '0'] - else - values = super() - if values.is_a?(Array) - values.each do |value| - value.force_encoding('UTF-8') if value.respond_to?(:force_encoding) - end - values - else - [] + def possible_values + values = super() + if values.is_a?(Array) + values.each do |value| + value.force_encoding('UTF-8') if value.respond_to?(:force_encoding) end + values + else + [] end end @@ -140,24 +135,7 @@ class CustomField < ActiveRecord::Base end def cast_value(value) - casted = nil - unless value.blank? - case field_format - when 'string', 'text', 'list' - casted = value - when 'date' - casted = begin; value.to_date; rescue; nil end - when 'bool' - casted = (value == '1' ? true : false) - when 'int' - casted = value.to_i - when 'float' - casted = value.to_f - when 'user', 'version' - casted = (value.blank? ? nil : field_format.classify.constantize.find_by_id(value.to_i)) - end - end - casted + format.cast_value(self, value) end def value_from_keyword(keyword, customized) @@ -181,83 +159,18 @@ class CustomField < ActiveRecord::Base # Returns nil if the custom field can not be used for sorting. def order_statement return nil if multiple? - case field_format - when 'string', 'text', 'list', 'date', 'bool' - # COALESCE is here to make sure that blank and NULL values are sorted equally - "COALESCE(#{join_alias}.value, '')" - when 'int', 'float' - # Make the database cast values into numeric - # Postgresql will raise an error if a value can not be casted! - # CustomValue validations should ensure that it doesn't occur - "CAST(CASE #{join_alias}.value WHEN '' THEN '0' ELSE #{join_alias}.value END AS decimal(30,3))" - when 'user', 'version' - value_class.fields_for_order_statement(value_join_alias) - else - nil - end + format.order_statement(self) end # Returns a GROUP BY clause that can used to group by custom value # Returns nil if the custom field can not be used for grouping. def group_statement return nil if multiple? - case field_format - when 'list', 'date', 'bool', 'int' - order_statement - when 'user', 'version' - "COALESCE(#{join_alias}.value, '')" - else - nil - end + format.group_statement(self) end def join_for_order_statement - case field_format - when 'user', 'version' - "LEFT OUTER JOIN #{CustomValue.table_name} #{join_alias}" + - " ON #{join_alias}.customized_type = '#{self.class.customized_class.base_class.name}'" + - " AND #{join_alias}.customized_id = #{self.class.customized_class.table_name}.id" + - " AND #{join_alias}.custom_field_id = #{id}" + - " AND (#{visibility_by_project_condition})" + - " AND #{join_alias}.value <> ''" + - " AND #{join_alias}.id = (SELECT max(#{join_alias}_2.id) FROM #{CustomValue.table_name} #{join_alias}_2" + - " WHERE #{join_alias}_2.customized_type = #{join_alias}.customized_type" + - " AND #{join_alias}_2.customized_id = #{join_alias}.customized_id" + - " AND #{join_alias}_2.custom_field_id = #{join_alias}.custom_field_id)" + - " LEFT OUTER JOIN #{value_class.table_name} #{value_join_alias}" + - " ON CAST(CASE #{join_alias}.value WHEN '' THEN '0' ELSE #{join_alias}.value END AS decimal(30,0)) = #{value_join_alias}.id" - when 'int', 'float' - "LEFT OUTER JOIN #{CustomValue.table_name} #{join_alias}" + - " ON #{join_alias}.customized_type = '#{self.class.customized_class.base_class.name}'" + - " AND #{join_alias}.customized_id = #{self.class.customized_class.table_name}.id" + - " AND #{join_alias}.custom_field_id = #{id}" + - " AND (#{visibility_by_project_condition})" + - " AND #{join_alias}.value <> ''" + - " AND #{join_alias}.id = (SELECT max(#{join_alias}_2.id) FROM #{CustomValue.table_name} #{join_alias}_2" + - " WHERE #{join_alias}_2.customized_type = #{join_alias}.customized_type" + - " AND #{join_alias}_2.customized_id = #{join_alias}.customized_id" + - " AND #{join_alias}_2.custom_field_id = #{join_alias}.custom_field_id)" - when 'string', 'text', 'list', 'date', 'bool' - "LEFT OUTER JOIN #{CustomValue.table_name} #{join_alias}" + - " ON #{join_alias}.customized_type = '#{self.class.customized_class.base_class.name}'" + - " AND #{join_alias}.customized_id = #{self.class.customized_class.table_name}.id" + - " AND #{join_alias}.custom_field_id = #{id}" + - " AND (#{visibility_by_project_condition})" + - " AND #{join_alias}.id = (SELECT max(#{join_alias}_2.id) FROM #{CustomValue.table_name} #{join_alias}_2" + - " WHERE #{join_alias}_2.customized_type = #{join_alias}.customized_type" + - " AND #{join_alias}_2.customized_id = #{join_alias}.customized_id" + - " AND #{join_alias}_2.custom_field_id = #{join_alias}.custom_field_id)" - else - nil - end - end - - def join_alias - "cf_#{id}" - end - - def value_join_alias - join_alias + "_" + field_format + format.join_for_order_statement(self) end def visibility_by_project_condition(project_key=nil, user=User.current) @@ -293,12 +206,7 @@ class CustomField < ActiveRecord::Base # Returns the class that values represent def value_class - case field_format - when 'user', 'version' - field_format.classify.constantize - else - nil - end + format.target_class if format.respond_to?(:target_class) end def self.customized_class @@ -317,7 +225,8 @@ class CustomField < ActiveRecord::Base # Returns the error messages for the given value # or an empty array if value is a valid value for the custom field - def validate_field_value(value) + def validate_custom_value(custom_value) + value = custom_value.value errs = [] if value.is_a?(Array) if !multiple? @@ -326,16 +235,22 @@ class CustomField < ActiveRecord::Base if is_required? && value.detect(&:present?).nil? errs << ::I18n.t('activerecord.errors.messages.blank') end - value.each {|v| errs += validate_field_value_format(v)} else if is_required? && value.blank? errs << ::I18n.t('activerecord.errors.messages.blank') end - errs += validate_field_value_format(value) + end + if custom_value.value.present? + errs += format.validate_custom_value(custom_value) end errs end + # Returns the error messages for the default custom field value + def validate_field_value(value) + validate_custom_value(CustomValue.new(:custom_field => self, :value => value)) + end + # Returns true if value is a valid value for the custom field def valid_field_value?(value) validate_field_value(value).empty? @@ -347,29 +262,6 @@ class CustomField < ActiveRecord::Base protected - # Returns the error message for the given value regarding its format - def validate_field_value_format(value) - errs = [] - if value.present? - errs << ::I18n.t('activerecord.errors.messages.invalid') unless regexp.blank? or value =~ Regexp.new(regexp) - errs << ::I18n.t('activerecord.errors.messages.too_short', :count => min_length) if min_length > 0 and value.length < min_length - errs << ::I18n.t('activerecord.errors.messages.too_long', :count => max_length) if max_length > 0 and value.length > max_length - - # Format specific validations - case field_format - when 'int' - errs << ::I18n.t('activerecord.errors.messages.not_a_number') unless value =~ /^[+-]?\d+$/ - when 'float' - begin; Kernel.Float(value); rescue; errs << ::I18n.t('activerecord.errors.messages.invalid') end - when 'date' - errs << ::I18n.t('activerecord.errors.messages.not_a_date') unless value =~ /^\d{4}-\d{2}-\d{2}$/ && begin; value.to_date; rescue; false end - when 'list' - errs << ::I18n.t('activerecord.errors.messages.inclusion') unless possible_values.include?(value) - end - end - errs - end - # Removes multiple values for the custom field after setting the multiple attribute to false # We kepp the value with the highest id for each customized object def handle_multiplicity_change diff --git a/app/models/custom_field_value.rb b/app/models/custom_field_value.rb index 04288b117..38033e2e1 100644 --- a/app/models/custom_field_value.rb +++ b/app/models/custom_field_value.rb @@ -16,7 +16,13 @@ # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. class CustomFieldValue - attr_accessor :custom_field, :customized, :value + attr_accessor :custom_field, :customized, :value, :value_was + + def initialize(attributes={}) + attributes.each do |name, v| + send "#{name}=", v + end + end def custom_field_id custom_field.id @@ -43,7 +49,7 @@ class CustomFieldValue end def validate_value - custom_field.validate_field_value(value).each do |message| + custom_field.validate_custom_value(self).each do |message| customized.errors.add(:base, custom_field.name + ' ' + message) end end diff --git a/app/models/query.rb b/app/models/query.rb index 7582d73bc..9adc43f13 100644 --- a/app/models/query.rb +++ b/app/models/query.rb @@ -587,7 +587,7 @@ class Query < ActiveRecord::Base db_field = 'value' filter = @available_filters[field] return nil unless filter - if filter[:format] == 'user' + if filter[:field].format.target_class && filter[:field].format.target_class <= User if value.delete('me') value.push User.current.id.to_s end @@ -764,29 +764,13 @@ class Query < ActiveRecord::Base # Adds a filter for the given custom field def add_custom_field_filter(field, assoc=nil) - case field.field_format - when "text" - options = { :type => :text } - when "list" - options = { :type => :list_optional, :values => field.possible_values } - when "date" - options = { :type => :date } - when "bool" - options = { :type => :list, :values => [[l(:general_text_yes), "1"], [l(:general_text_no), "0"]] } - when "int" - options = { :type => :integer } - when "float" - options = { :type => :float } - when "user", "version" - return unless project - values = field.possible_values_options(project) - if User.current.logged? && field.field_format == 'user' - values.unshift ["<< #{l(:label_me)} >>", "me"] + options = field.format.query_filter_options(field, self) + if field.format.target_class && field.format.target_class <= User + if options[:values].is_a?(Array) && User.current.logged? + options[:values].unshift ["<< #{l(:label_me)} >>", "me"] end - options = { :type => :list_optional, :values => values } - else - options = { :type => :string } end + filter_id = "cf_#{field.id}" filter_name = field.name if assoc.present? @@ -795,7 +779,6 @@ class Query < ActiveRecord::Base end add_available_filter filter_id, options.merge({ :name => filter_name, - :format => field.field_format, :field => field }) end diff --git a/app/views/custom_fields/_form.html.erb b/app/views/custom_fields/_form.html.erb index 356d0bca3..a6417bb53 100644 --- a/app/views/custom_fields/_form.html.erb +++ b/app/views/custom_fields/_form.html.erb @@ -1,14 +1,12 @@ <%= error_messages_for 'custom_field' %> -<% if @custom_field.is_a?(IssueCustomField) %>
-<% end %> -

<%= f.text_field :name, :required => true %>

+

<%= f.text_area :description, :rows => 7 %>

<%= f.select :field_format, custom_field_formats_for_select(@custom_field), {}, :disabled => !@custom_field.new_record? %>

-<% if @custom_field.format_in? 'list', 'user', 'version' %> +<% if @custom_field.format.multiple_supported %>

<%= f.check_box :multiple %> <% if !@custom_field.new_record? && @custom_field.multiple %> @@ -17,56 +15,38 @@

<% end %> -<% unless @custom_field.format_in? 'list', 'bool', 'date', 'user', 'version' %> -

- <%= f.text_field :min_length, :size => 5, :no_label => true %> - - <%= f.text_field :max_length, :size => 5, :no_label => true %>
(<%=l(:text_min_max_length_info)%>)

-

<%= f.text_field :regexp, :size => 50 %>
(<%=l(:text_regexp_info)%>)

-<% end %> - -<% if @custom_field.format_in? 'list' %> -

- <%= f.text_area :possible_values, :value => @custom_field.possible_values.to_a.join("\n"), :rows => 15 %> - <%= l(:text_custom_field_possible_values_info) %> -

-<% end %> - -<% case @custom_field.field_format %> -<% when 'bool' %> -

<%= f.check_box(:default_value) %>

-<% when 'text' %> -

<%= f.text_area(:default_value, :rows => 8) %>

-<% when 'date' %> -

<%= f.text_field(:default_value, :size => 10) %>

- <%= calendar_for('custom_field_default_value') %> -<% when 'user', 'version' %> -<% else %> -

<%= f.text_field(:default_value) %>

-<% end %> +<%= render_custom_field_format_partial f, @custom_field %> <%= call_hook(:view_custom_fields_form_upper_box, :custom_field => @custom_field, :form => f) %>
+

<%= submit_tag l(:button_save) %>

+
+
<% case @custom_field.class.name when "IssueCustomField" %>

<%= f.check_box :is_required %>

-

<%= f.check_box :is_for_all %>

+

<%= f.check_box :is_for_all, :data => {:disables => '#custom_field_project_ids input'} %>

<%= f.check_box :is_filter %>

+ <% if @custom_field.format.searchable_supported %>

<%= f.check_box :searchable %>

+ <% end %>

<% Role.givable.sorted.each do |role| %> <% end %> @@ -82,7 +62,9 @@ when "IssueCustomField" %> <% when "ProjectCustomField" %>

<%= f.check_box :is_required %>

<%= f.check_box :visible %>

+ <% if @custom_field.format.searchable_supported %>

<%= f.check_box :searchable %>

+ <% end %>

<%= f.check_box :is_filter %>

<% when "VersionCustomField" %> @@ -103,12 +85,9 @@ when "IssueCustomField" %> <% end %> <%= call_hook(:"view_custom_fields_form_#{@custom_field.type.to_s.underscore}", :custom_field => @custom_field, :form => f) %>
-<%= submit_tag l(:button_save) %> <% if @custom_field.is_a?(IssueCustomField) %> -
-
-
<%=l(:label_tracker_plural)%> +
<%=l(:label_tracker_plural)%> <% Tracker.sorted.all.each do |tracker| %> <%= check_box_tag "custom_field[tracker_ids][]", tracker.id, @@ -119,6 +98,7 @@ when "IssueCustomField" %> <% end %> <%= hidden_field_tag "custom_field[tracker_ids][]", '' %> +

<%= check_all_links 'custom_field_tracker_ids' %>

<%= l(:label_project_plural) %> @@ -128,20 +108,7 @@ when "IssueCustomField" %> <%= hidden_field_tag('custom_field[project_ids][]', '', :id => nil) %>

<%= check_all_links 'custom_field_project_ids' %>

-
<% end %> + <% include_calendar_headers_tags %> - -<%= javascript_tag do %> -function toggleCustomFieldRoles(){ - var checked = $("#custom_field_visible_on").is(':checked'); - $('.custom_field_role input').attr('disabled', checked); -} -$("#custom_field_visible_on, #custom_field_visible_off").change(toggleCustomFieldRoles); -$(document).ready(toggleCustomFieldRoles); - -$("#custom_field_is_for_all").change(function(){ - $("#custom_field_project_ids input").attr("disabled", $(this).is(":checked")); -}).trigger('change'); -<% end %> diff --git a/app/views/custom_fields/_index.html.erb b/app/views/custom_fields/_index.html.erb index d55d08cfc..4752c2519 100644 --- a/app/views/custom_fields/_index.html.erb +++ b/app/views/custom_fields/_index.html.erb @@ -14,7 +14,7 @@ <% (@custom_fields_by_type[tab[:name]] || []).sort.each do |custom_field| -%> "> <%= link_to h(custom_field.name), edit_custom_field_path(custom_field) %> - <%= l(Redmine::CustomFieldFormat.label_for(custom_field.field_format)) %> + <%= l(custom_field.format.label) %> <%= checked_image custom_field.is_required? %> <% if tab[:name] == 'IssueCustomField' %> <%= checked_image custom_field.is_for_all? %> diff --git a/app/views/custom_fields/formats/_bool.html.erb b/app/views/custom_fields/formats/_bool.html.erb new file mode 100644 index 000000000..25c464fb9 --- /dev/null +++ b/app/views/custom_fields/formats/_bool.html.erb @@ -0,0 +1,2 @@ +

<%= f.select :default_value, [[]]+@custom_field.possible_values_options %>

+

<%= edit_tag_style_tag f %>

diff --git a/app/views/custom_fields/formats/_date.html.erb b/app/views/custom_fields/formats/_date.html.erb new file mode 100644 index 000000000..807a9269e --- /dev/null +++ b/app/views/custom_fields/formats/_date.html.erb @@ -0,0 +1,2 @@ +

<%= f.text_field(:default_value, :size => 10) %>

+<%= calendar_for('custom_field_default_value') %> diff --git a/app/views/custom_fields/formats/_link.html.erb b/app/views/custom_fields/formats/_link.html.erb new file mode 100644 index 000000000..9b7d342e0 --- /dev/null +++ b/app/views/custom_fields/formats/_link.html.erb @@ -0,0 +1,3 @@ +<%= render :partial => 'custom_fields/formats/regexp', :locals => {:f => f, :custom_field => custom_field} %> +

<%= f.text_field :url_pattern, :size => 50, :label => :field_url %>

+

<%= f.text_field(:default_value) %>

diff --git a/app/views/custom_fields/formats/_list.html.erb b/app/views/custom_fields/formats/_list.html.erb new file mode 100644 index 000000000..9bbd6a243 --- /dev/null +++ b/app/views/custom_fields/formats/_list.html.erb @@ -0,0 +1,6 @@ +

+ <%= f.text_area :possible_values, :value => @custom_field.possible_values.to_a.join("\n"), :rows => 15 %> + <%= l(:text_custom_field_possible_values_info) %> +

+

<%= f.text_field(:default_value) %>

+

<%= edit_tag_style_tag f %>

diff --git a/app/views/custom_fields/formats/_numeric.html.erb b/app/views/custom_fields/formats/_numeric.html.erb new file mode 100644 index 000000000..06187485d --- /dev/null +++ b/app/views/custom_fields/formats/_numeric.html.erb @@ -0,0 +1,2 @@ +<%= render :partial => 'custom_fields/formats/regexp', :locals => {:f => f, :custom_field => custom_field} %> +

<%= f.text_field(:default_value) %>

diff --git a/app/views/custom_fields/formats/_regexp.html.erb b/app/views/custom_fields/formats/_regexp.html.erb new file mode 100644 index 000000000..0b630347a --- /dev/null +++ b/app/views/custom_fields/formats/_regexp.html.erb @@ -0,0 +1,10 @@ +

+ + <%= f.text_field :min_length, :size => 5, :no_label => true %> - + <%= f.text_field :max_length, :size => 5, :no_label => true %> + <%= l(:text_min_max_length_info) %> +

+

+ <%= f.text_field :regexp, :size => 50 %> + <%= l(:text_regexp_info) %> +

diff --git a/app/views/custom_fields/formats/_string.html.erb b/app/views/custom_fields/formats/_string.html.erb new file mode 100644 index 000000000..0c71243a8 --- /dev/null +++ b/app/views/custom_fields/formats/_string.html.erb @@ -0,0 +1,3 @@ +<%= render :partial => 'custom_fields/formats/regexp', :locals => {:f => f, :custom_field => custom_field} %> +

<%= f.check_box :text_formatting, {:label => :setting_text_formatting}, 'full', '' %>

+

<%= f.text_field(:default_value) %>

diff --git a/app/views/custom_fields/formats/_text.html.erb b/app/views/custom_fields/formats/_text.html.erb new file mode 100644 index 000000000..e72dcab42 --- /dev/null +++ b/app/views/custom_fields/formats/_text.html.erb @@ -0,0 +1,3 @@ +<%= render :partial => 'custom_fields/formats/regexp', :locals => {:f => f, :custom_field => custom_field} %> +

<%= f.check_box :text_formatting, {:label => :setting_text_formatting}, 'full', '' %>

+

<%= f.text_area(:default_value, :rows => 5) %>

diff --git a/app/views/custom_fields/formats/_user.html.erb b/app/views/custom_fields/formats/_user.html.erb new file mode 100644 index 000000000..3bb4d29c0 --- /dev/null +++ b/app/views/custom_fields/formats/_user.html.erb @@ -0,0 +1,24 @@ +

+ + + + <% Role.givable.sorted.each do |role| %> + + <% end %> + <%= hidden_field_tag 'custom_field[user_role][]', '' %> +

+

<%= edit_tag_style_tag f %>

diff --git a/app/views/custom_fields/formats/_version.html.erb b/app/views/custom_fields/formats/_version.html.erb new file mode 100644 index 000000000..b8060d20e --- /dev/null +++ b/app/views/custom_fields/formats/_version.html.erb @@ -0,0 +1,24 @@ +

+ + + + <% Version::VERSION_STATUSES.each do |status| %> + + <% end %> + <%= hidden_field_tag 'custom_field[version_status][]', '' %> +

+

<%= edit_tag_style_tag f %>

diff --git a/app/views/custom_fields/new.html.erb b/app/views/custom_fields/new.html.erb index 69328412e..6c5809e73 100644 --- a/app/views/custom_fields/new.html.erb +++ b/app/views/custom_fields/new.html.erb @@ -12,7 +12,8 @@ $('#custom_field_field_format').change(function(){ $.ajax({ url: '<%= new_custom_field_path(:format => 'js') %>', type: 'get', - data: $('#custom_field_form').serialize() + data: $('#custom_field_form').serialize(), + complete: toggleDisabledInit }); }); <% end %> diff --git a/app/views/issues/bulk_edit.html.erb b/app/views/issues/bulk_edit.html.erb index a8c04a9c4..2b063f957 100644 --- a/app/views/issues/bulk_edit.html.erb +++ b/app/views/issues/bulk_edit.html.erb @@ -93,7 +93,7 @@ <% @custom_fields.each do |custom_field| %>

- <%= custom_field_tag_for_bulk_edit('issue', custom_field, @projects, @issue_params[:custom_field_values][custom_field.id.to_s]) %> + <%= custom_field_tag_for_bulk_edit('issue', custom_field, @issues, @issue_params[:custom_field_values][custom_field.id.to_s]) %>

<% end %> diff --git a/app/views/timelog/bulk_edit.html.erb b/app/views/timelog/bulk_edit.html.erb index 60836e118..a34a9afc1 100644 --- a/app/views/timelog/bulk_edit.html.erb +++ b/app/views/timelog/bulk_edit.html.erb @@ -39,7 +39,7 @@

<% @custom_fields.each do |custom_field| %> -

<%= custom_field_tag_for_bulk_edit('time_entry', custom_field, @projects) %>

+

<%= custom_field_tag_for_bulk_edit('time_entry', custom_field, @time_entries) %>

<% end %> <%= call_hook(:view_time_entries_bulk_edit_details_bottom, { :time_entries => @time_entries }) %> diff --git a/db/migrate/20131124175346_add_custom_fields_format_store.rb b/db/migrate/20131124175346_add_custom_fields_format_store.rb new file mode 100644 index 000000000..47c7b313a --- /dev/null +++ b/db/migrate/20131124175346_add_custom_fields_format_store.rb @@ -0,0 +1,9 @@ +class AddCustomFieldsFormatStore < ActiveRecord::Migration + def up + add_column :custom_fields, :format_store, :text + end + + def down + remove_column :custom_fields, :format_store + end +end diff --git a/db/migrate/20131210180802_add_custom_fields_description.rb b/db/migrate/20131210180802_add_custom_fields_description.rb new file mode 100644 index 000000000..8a5d9809d --- /dev/null +++ b/db/migrate/20131210180802_add_custom_fields_description.rb @@ -0,0 +1,9 @@ +class AddCustomFieldsDescription < ActiveRecord::Migration + def up + add_column :custom_fields, :description, :text + end + + def down + remove_column :custom_fields, :description + end +end diff --git a/lib/plugins/acts_as_customizable/lib/acts_as_customizable.rb b/lib/plugins/acts_as_customizable/lib/acts_as_customizable.rb index 1f1aa1e44..3575cc550 100644 --- a/lib/plugins/acts_as_customizable/lib/acts_as_customizable.rb +++ b/lib/plugins/acts_as_customizable/lib/acts_as_customizable.rb @@ -99,6 +99,7 @@ module Redmine cv ||= custom_values.build(:customized => self, :custom_field => field, :value => nil) x.value = cv.value end + x.value_was = x.value.dup if x.value x end end diff --git a/lib/redmine.rb b/lib/redmine.rb index 43e3f146a..f7916172b 100644 --- a/lib/redmine.rb +++ b/lib/redmine.rb @@ -30,7 +30,6 @@ require 'redmine/activity' require 'redmine/activity/fetcher' require 'redmine/ciphering' require 'redmine/codeset_util' -require 'redmine/custom_field_format' require 'redmine/i18n' require 'redmine/menu_manager' require 'redmine/notifiable' @@ -73,18 +72,6 @@ Redmine::Scm::Base.add "Bazaar" Redmine::Scm::Base.add "Git" Redmine::Scm::Base.add "Filesystem" -Redmine::CustomFieldFormat.map do |fields| - fields.register 'string' - fields.register 'text' - fields.register 'int', :label => :label_integer - fields.register 'float' - fields.register 'list' - fields.register 'date' - fields.register 'bool', :label => :label_boolean - fields.register 'user', :only => %w(Issue TimeEntry Version Project), :edit_as => 'list' - fields.register 'version', :only => %w(Issue TimeEntry Version Project), :edit_as => 'list' -end - # Permissions Redmine::AccessControl.map do |map| map.permission :view_project, {:projects => [:show], :activities => [:index]}, :public => true, :read => true diff --git a/lib/redmine/custom_field_format.rb b/lib/redmine/custom_field_format.rb deleted file mode 100644 index c539aee2e..000000000 --- a/lib/redmine/custom_field_format.rb +++ /dev/null @@ -1,115 +0,0 @@ -# Redmine - project management software -# Copyright (C) 2006-2013 Jean-Philippe Lang -# -# This program is free software; you can redistribute it and/or -# modify it under the terms of the GNU General Public License -# as published by the Free Software Foundation; either version 2 -# of the License, or (at your option) any later version. -# -# This program is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU General Public License for more details. -# -# You should have received a copy of the GNU General Public License -# along with this program; if not, write to the Free Software -# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - -module Redmine - class CustomFieldFormat - include Redmine::I18n - - cattr_accessor :available - @@available = {} - - attr_accessor :name, :order, :label, :edit_as, :class_names - - def initialize(name, options={}) - self.name = name - self.label = options[:label] || "label_#{name}".to_sym - self.order = options[:order] || self.class.available_formats.size - self.edit_as = options[:edit_as] || name - self.class_names = options[:only] - end - - def format(value) - send "format_as_#{name}", value - end - - def format_as_date(value) - begin; format_date(value.to_date); rescue; value end - end - - def format_as_bool(value) - l(value == "1" ? :general_text_Yes : :general_text_No) - end - - ['string','text','int','float','list'].each do |name| - define_method("format_as_#{name}") {|value| - return value - } - end - - ['user', 'version'].each do |name| - define_method("format_as_#{name}") {|value| - return value.blank? ? "" : name.classify.constantize.find_by_id(value.to_i).to_s - } - end - - class << self - def map(&block) - yield self - end - - # Registers a custom field format - def register(*args) - custom_field_format = args.first - unless custom_field_format.is_a?(Redmine::CustomFieldFormat) - custom_field_format = Redmine::CustomFieldFormat.new(*args) - end - @@available[custom_field_format.name] = custom_field_format unless @@available.keys.include?(custom_field_format.name) - end - - def delete(format) - if format.is_a?(Redmine::CustomFieldFormat) - format = format.name - end - @@available.delete(format) - end - - def available_formats - @@available.keys - end - - def find_by_name(name) - @@available[name.to_s] - end - - def label_for(name) - format = @@available[name.to_s] - format.label if format - end - - # Return an array of custom field formats which can be used in select_tag - def as_select(class_name=nil) - fields = @@available.values - fields = fields.select {|field| field.class_names.nil? || field.class_names.include?(class_name)} - fields.sort {|a,b| - a.order <=> b.order - }.collect {|custom_field_format| - [ l(custom_field_format.label), custom_field_format.name ] - } - end - - def format_value(value, field_format) - return "" unless value && !value.empty? - - if format_type = find_by_name(field_format) - format_type.format(value) - else - value - end - end - end - end -end diff --git a/lib/redmine/export/pdf.rb b/lib/redmine/export/pdf.rb index 193319aa5..80f633e0f 100644 --- a/lib/redmine/export/pdf.rb +++ b/lib/redmine/export/pdf.rb @@ -257,7 +257,7 @@ module Redmine query.inline_columns.collect do |column| s = if column.is_a?(QueryCustomFieldColumn) cv = issue.visible_custom_field_values.detect {|v| v.custom_field_id == column.custom_field.id} - show_value(cv) + show_value(cv, false) else value = issue.send(column.name) if column.name == :subject @@ -573,7 +573,7 @@ module Redmine half = (issue.visible_custom_field_values.size / 2.0).ceil issue.visible_custom_field_values.each_with_index do |custom_value, i| - (i < half ? left : right) << [custom_value.custom_field.name, show_value(custom_value)] + (i < half ? left : right) << [custom_value.custom_field.name, show_value(custom_value, false)] end rows = left.size > right.size ? left.size : right.size diff --git a/lib/redmine/field_format.rb b/lib/redmine/field_format.rb new file mode 100644 index 000000000..5ff11939a --- /dev/null +++ b/lib/redmine/field_format.rb @@ -0,0 +1,646 @@ +# Redmine - project management software +# Copyright (C) 2006-2013 Jean-Philippe Lang +# +# This program is free software; you can redistribute it and/or +# modify it under the terms of the GNU General Public License +# as published by the Free Software Foundation; either version 2 +# of the License, or (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software +# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + +module Redmine + module FieldFormat + def self.add(name, klass) + all[name.to_s] = klass.instance + end + + def self.delete(name) + all.delete(name.to_s) + end + + def self.all + @formats ||= Hash.new(Base.instance) + end + + def self.available_formats + all.keys + end + + def self.find(name) + all[name.to_s] + end + + # Return an array of custom field formats which can be used in select_tag + def self.as_select(class_name=nil) + formats = all.values + formats.select! do |format| + format.class.customized_class_names.nil? || format.class.customized_class_names.include?(class_name) + end + formats.map {|format| [::I18n.t(format.label), format.name] }.sort_by(&:first) + end + + class Base + include Singleton + include Redmine::I18n + include ERB::Util + + class_attribute :format_name + self.format_name = nil + + # Set this to true if the format supports multiple values + class_attribute :multiple_supported + self.multiple_supported = false + + # Set this to true if the format supports textual search on custom values + class_attribute :searchable_supported + self.searchable_supported = false + + # Restricts the classes that the custom field can be added to + # Set to nil for no restrictions + class_attribute :customized_class_names + self.customized_class_names = nil + + # Name of the partial for editing the custom field + class_attribute :form_partial + self.form_partial = nil + + def self.add(name) + self.format_name = name + Redmine::FieldFormat.add(name, self) + end + private_class_method :add + + def self.field_attributes(*args) + CustomField.store_accessor :format_store, *args + end + + def name + self.class.format_name + end + + def label + "label_#{name}" + end + + def cast_custom_value(custom_value) + cast_value(custom_value.custom_field, custom_value.value, custom_value.customized) + end + + def cast_value(custom_field, value, customized=nil) + if value.blank? + nil + elsif value.is_a?(Array) + value.map do |v| + cast_single_value(custom_field, v, customized) + end.sort + else + cast_single_value(custom_field, value, customized) + end + end + + def cast_single_value(custom_field, value, customized=nil) + value.to_s + end + + def target_class + nil + end + + def possible_custom_value_options(custom_value) + possible_values_options(custom_value.custom_field, custom_value.customized) + end + + def possible_values_options(custom_field, object=nil) + custom_field.possible_values + end + + # Returns the validation errors for custom_field + # Should return an empty array if custom_field is valid + def validate_custom_field(custom_field) + [] + end + + # Returns the validation error messages for custom_value + # Should return an empty array if custom_value is valid + def validate_custom_value(custom_value) + errors = Array.wrap(custom_value.value).reject(&:blank?).map do |value| + validate_single_value(custom_value.custom_field, value, custom_value.customized) + end + errors.flatten.uniq + end + + def validate_single_value(custom_field, value, customized=nil) + [] + end + + def formatted_custom_value(view, custom_value, html=false) + formatted_value(view, custom_value.custom_field, custom_value.value, custom_value.customized, html) + end + + def formatted_value(view, custom_field, value, customized=nil, html=false) + cast_value(custom_field, value, customized) + end + + def edit_tag(view, tag_id, tag_name, custom_value, options={}) + view.text_field_tag(tag_name, custom_value.value, options.merge(:id => tag_id)) + end + + def bulk_edit_tag(view, tag_id, tag_name, custom_field, objects, value, options={}) + view.text_field_tag(tag_name, value, options.merge(:id => tag_id)) + + bulk_clear_tag(view, tag_id, tag_name, custom_field, value) + end + + def bulk_clear_tag(view, tag_id, tag_name, custom_field, value) + if custom_field.is_required? + ''.html_safe + else + view.content_tag('label', + view.check_box_tag(tag_name, '__none__', (value == '__none__'), :id => nil, :data => {:disables => "##{tag_id}"}) + l(:button_clear), + :class => 'inline' + ) + end + end + protected :bulk_clear_tag + + def query_filter_options(custom_field, query) + {:type => :string} + end + + def before_custom_field_save(custom_field) + end + + # Returns a ORDER BY clause that can used to sort customized + # objects by their value of the custom field. + # Returns nil if the custom field can not be used for sorting. + def order_statement(custom_field) + # COALESCE is here to make sure that blank and NULL values are sorted equally + "COALESCE(#{join_alias custom_field}.value, '')" + end + + # Returns a GROUP BY clause that can used to group by custom value + # Returns nil if the custom field can not be used for grouping. + def group_statement(custom_field) + nil + end + + # Returns a JOIN clause that is added to the query when sorting by custom values + def join_for_order_statement(custom_field) + alias_name = join_alias(custom_field) + + "LEFT OUTER JOIN #{CustomValue.table_name} #{alias_name}" + + " ON #{alias_name}.customized_type = '#{custom_field.class.customized_class.base_class.name}'" + + " AND #{alias_name}.customized_id = #{custom_field.class.customized_class.table_name}.id" + + " AND #{alias_name}.custom_field_id = #{custom_field.id}" + + " AND (#{custom_field.visibility_by_project_condition})" + + " AND #{alias_name}.value <> ''" + + " AND #{alias_name}.id = (SELECT max(#{alias_name}_2.id) FROM #{CustomValue.table_name} #{alias_name}_2" + + " WHERE #{alias_name}_2.customized_type = #{alias_name}.customized_type" + + " AND #{alias_name}_2.customized_id = #{alias_name}.customized_id" + + " AND #{alias_name}_2.custom_field_id = #{alias_name}.custom_field_id)" + end + + def join_alias(custom_field) + "cf_#{custom_field.id}" + end + protected :join_alias + end + + class Unbounded < Base + def validate_single_value(custom_field, value, customized=nil) + errs = super + if value.present? + unless custom_field.regexp.blank? or value =~ Regexp.new(custom_field.regexp) + errs << ::I18n.t('activerecord.errors.messages.invalid') + end + if custom_field.min_length > 0 and value.length < custom_field.min_length + errs << ::I18n.t('activerecord.errors.messages.too_short', :count => custom_field.min_length) + end + if custom_field.max_length > 0 and value.length > custom_field.max_length + errs << ::I18n.t('activerecord.errors.messages.too_long', :count => custom_field.max_length) + end + end + errs + end + end + + class StringFormat < Unbounded + add 'string' + self.searchable_supported = true + self.form_partial = 'custom_fields/formats/string' + field_attributes :text_formatting + + def formatted_value(view, custom_field, value, customized=nil, html=false) + if html && custom_field.text_formatting == 'full' + view.textilizable(value, :object => customized) + else + value.to_s + end + end + end + + class TextFormat < Unbounded + add 'text' + self.searchable_supported = true + self.form_partial = 'custom_fields/formats/text' + + def formatted_value(view, custom_field, value, customized=nil, html=false) + if html + if custom_field.text_formatting == 'full' + view.textilizable(value, :object => customized) + else + view.simple_format(html_escape(value)) + end + else + value.to_s + end + end + + def edit_tag(view, tag_id, tag_name, custom_value, options={}) + view.text_area_tag(tag_name, custom_value.value, options.merge(:id => tag_id, :rows => 3)) + end + + def bulk_edit_tag(view, tag_id, tag_name, custom_field, objects, value, options={}) + view.text_area_tag(tag_name, value, options.merge(:id => tag_id, :rows => 3)) + + '
'.html_safe + + bulk_clear_tag(view, tag_id, tag_name, custom_field, value) + end + + def query_filter_options(custom_field, query) + {:type => :text} + end + end + + class LinkFormat < StringFormat + add 'link' + self.searchable_supported = false + self.form_partial = 'custom_fields/formats/link' + field_attributes :url_pattern + + def formatted_value(view, custom_field, value, customized=nil, html=false) + if html + if custom_field.url_pattern.present? + url = custom_field.url_pattern.to_s.dup + url.gsub!('%value%') {value.to_s} + url.gsub!('%id%') {customized.id.to_s} + url.gsub!('%project_id%') {(customized.respond_to?(:project) ? customized.project.try(:id) : nil).to_s} + if custom_field.regexp.present? + url.gsub!(%r{%m(\d+)%}) do + m = $1.to_i + matches ||= value.to_s.match(Regexp.new(custom_field.regexp)) + matches[m].to_s if matches + end + end + else + url = value.to_s + unless url =~ %r{\A[a-z]+://}i + # no protocol found, use http by default + url = "http://" + url + end + end + view.link_to value.to_s, url + else + value.to_s + end + end + end + + class Numeric < Unbounded + self.form_partial = 'custom_fields/formats/numeric' + + def order_statement(custom_field) + # Make the database cast values into numeric + # Postgresql will raise an error if a value can not be casted! + # CustomValue validations should ensure that it doesn't occur + "CAST(CASE #{join_alias custom_field}.value WHEN '' THEN '0' ELSE #{join_alias custom_field}.value END AS decimal(30,3))" + end + end + + class IntFormat < Numeric + add 'int' + + def label + "label_integer" + end + + def cast_single_value(custom_field, value, customized=nil) + value.to_i + end + + def validate_single_value(custom_field, value, customized=nil) + errs = super + errs << ::I18n.t('activerecord.errors.messages.not_a_number') unless value =~ /^[+-]?\d+$/ + errs + end + + def query_filter_options(custom_field, query) + {:type => :integer} + end + + def group_statement(custom_field) + order_statement(custom_field) + end + end + + class FloatFormat < Numeric + add 'float' + + def cast_single_value(custom_field, value, customized=nil) + value.to_f + end + + def validate_single_value(custom_field, value, customized=nil) + errs = super + errs << ::I18n.t('activerecord.errors.messages.invalid') unless (Kernel.Float(value) rescue nil) + errs + end + + def query_filter_options(custom_field, query) + {:type => :float} + end + end + + class DateFormat < Unbounded + add 'date' + self.form_partial = 'custom_fields/formats/date' + + def cast_single_value(custom_field, value, customized=nil) + value.to_date rescue nil + end + + def validate_single_value(custom_field, value, customized=nil) + if value =~ /^\d{4}-\d{2}-\d{2}$/ && (value.to_date rescue false) + [] + else + [::I18n.t('activerecord.errors.messages.not_a_date')] + end + end + + def edit_tag(view, tag_id, tag_name, custom_value, options={}) + view.text_field_tag(tag_name, custom_value.value, options.merge(:id => tag_id, :size => 10)) + + view.calendar_for(tag_id) + end + + def bulk_edit_tag(view, tag_id, tag_name, custom_field, objects, value, options={}) + view.text_field_tag(tag_name, value, options.merge(:id => tag_id, :size => 10)) + + view.calendar_for(tag_id) + + bulk_clear_tag(view, tag_id, tag_name, custom_field, value) + end + + def query_filter_options(custom_field, query) + {:type => :date} + end + + def group_statement(custom_field) + order_statement(custom_field) + end + end + + class List < Base + self.multiple_supported = true + field_attributes :edit_tag_style + + def edit_tag(view, tag_id, tag_name, custom_value, options={}) + if custom_value.custom_field.edit_tag_style == 'check_box' + check_box_edit_tag(view, tag_id, tag_name, custom_value, options) + else + select_edit_tag(view, tag_id, tag_name, custom_value, options) + end + end + + def bulk_edit_tag(view, tag_id, tag_name, custom_field, objects, value, options={}) + opts = [] + opts << [l(:label_no_change_option), ''] unless custom_field.multiple? + opts << [l(:label_none), '__none__'] unless custom_field.is_required? + opts += possible_values_options(custom_field, objects) + view.select_tag(tag_name, view.options_for_select(opts, value), options.merge(:multiple => custom_field.multiple?)) + end + + def query_filter_options(custom_field, query) + {:type => :list_optional, :values => possible_values_options(custom_field, query.project)} + end + + protected + + # Renders the edit tag as a select tag + def select_edit_tag(view, tag_id, tag_name, custom_value, options={}) + blank_option = ''.html_safe + unless custom_value.custom_field.multiple? + if custom_value.custom_field.is_required? + unless custom_value.custom_field.default_value.present? + blank_option = view.content_tag('option', "--- #{l(:actionview_instancetag_blank_option)} ---", :value => '') + end + else + blank_option = view.content_tag('option', ' '.html_safe, :value => '') + end + end + options_tags = blank_option + view.options_for_select(possible_custom_value_options(custom_value), custom_value.value) + s = view.select_tag(tag_name, options_tags, options.merge(:id => tag_id, :multiple => custom_value.custom_field.multiple?)) + if custom_value.custom_field.multiple? + s << view.hidden_field_tag(tag_name, '') + end + s + end + + # Renders the edit tag as check box or radio tags + def check_box_edit_tag(view, tag_id, tag_name, custom_value, options={}) + opts = [] + unless custom_value.custom_field.multiple? || custom_value.custom_field.is_required? + opts << ["(#{l(:label_none)})", ''] + end + opts += possible_custom_value_options(custom_value) + s = ''.html_safe + tag_method = custom_value.custom_field.multiple? ? :check_box_tag : :radio_button_tag + opts.each do |label, value| + value ||= label + checked = (custom_value.value.is_a?(Array) && custom_value.value.include?(value)) || custom_value.value.to_s == value + tag = view.send(tag_method, tag_name, value, checked, :id => tag_id) + # set the id on the first tag only + tag_id = nil + s << view.content_tag('label', tag + ' ' + label) + end + css = "#{options[:class]} check_box_group" + view.content_tag('span', s, options.merge(:class => css)) + end + end + + class ListFormat < List + add 'list' + self.searchable_supported = true + self.form_partial = 'custom_fields/formats/list' + + def possible_custom_value_options(custom_value) + options = super + missing = [custom_value.value].flatten.reject(&:blank?) - options + if missing.any? + options += missing + end + options + end + + def validate_custom_field(custom_field) + errors = [] + errors << [:possible_values, :blank] if custom_field.possible_values.blank? + errors << [:possible_values, :invalid] unless custom_field.possible_values.is_a? Array + errors + end + + def validate_custom_value(custom_value) + invalid_values = Array.wrap(custom_value.value) - Array.wrap(custom_value.value_was) - custom_value.custom_field.possible_values + if invalid_values.select(&:present?).any? + [::I18n.t('activerecord.errors.messages.inclusion')] + else + [] + end + end + + def group_statement(custom_field) + order_statement(custom_field) + end + end + + class BoolFormat < List + add 'bool' + self.multiple_supported = false + self.form_partial = 'custom_fields/formats/bool' + + def label + "label_boolean" + end + + def cast_single_value(custom_field, value, customized=nil) + value == '1' ? true : false + end + + def possible_values_options(custom_field, object=nil) + [[::I18n.t(:general_text_Yes), '1'], [::I18n.t(:general_text_No), '0']] + end + + def group_statement(custom_field) + order_statement(custom_field) + end + end + + class RecordList < List + self.customized_class_names = %w(Issue TimeEntry Version Project) + + def cast_single_value(custom_field, value, customized=nil) + target_class.find_by_id(value.to_i) if value.present? + end + + def target_class + @target_class ||= self.class.name[/^(.*::)?(.+)Format$/, 2].constantize rescue nil + end + + def possible_custom_value_options(custom_value) + options = possible_values_options(custom_value.custom_field, custom_value.customized) + missing = [custom_value.value_was].flatten.reject(&:blank?) - options.map(&:last) + if missing.any? + options += target_class.find_all_by_id(missing.map(&:to_i)).map {|o| [o.to_s, o.id.to_s]} + options.sort_by!(&:first) + end + options + end + + def order_statement(custom_field) + if target_class.respond_to?(:fields_for_order_statement) + target_class.fields_for_order_statement(value_join_alias(custom_field)) + end + end + + def group_statement(custom_field) + "COALESCE(#{join_alias custom_field}.value, '')" + end + + def join_for_order_statement(custom_field) + alias_name = join_alias(custom_field) + + "LEFT OUTER JOIN #{CustomValue.table_name} #{alias_name}" + + " ON #{alias_name}.customized_type = '#{custom_field.class.customized_class.base_class.name}'" + + " AND #{alias_name}.customized_id = #{custom_field.class.customized_class.table_name}.id" + + " AND #{alias_name}.custom_field_id = #{custom_field.id}" + + " AND (#{custom_field.visibility_by_project_condition})" + + " AND #{alias_name}.value <> ''" + + " AND #{alias_name}.id = (SELECT max(#{alias_name}_2.id) FROM #{CustomValue.table_name} #{alias_name}_2" + + " WHERE #{alias_name}_2.customized_type = #{alias_name}.customized_type" + + " AND #{alias_name}_2.customized_id = #{alias_name}.customized_id" + + " AND #{alias_name}_2.custom_field_id = #{alias_name}.custom_field_id)" + + " LEFT OUTER JOIN #{target_class.table_name} #{value_join_alias custom_field}" + + " ON CAST(CASE #{alias_name}.value WHEN '' THEN '0' ELSE #{alias_name}.value END AS decimal(30,0)) = #{value_join_alias custom_field}.id" + end + + def value_join_alias(custom_field) + join_alias(custom_field) + "_" + custom_field.field_format + end + protected :value_join_alias + end + + class UserFormat < RecordList + add 'user' + self.form_partial = 'custom_fields/formats/user' + field_attributes :user_role + + def possible_values_options(custom_field, object=nil) + if object.is_a?(Array) + projects = object.map {|o| o.respond_to?(:project) ? o.project : nil}.compact.uniq + projects.map {|project| possible_values_options(custom_field, project)}.reduce(:&) || [] + elsif object.respond_to?(:project) && object.project + scope = object.project.users + if custom_field.user_role.is_a?(Array) + role_ids = custom_field.user_role.map(&:to_s).reject(&:blank?).map(&:to_i) + if role_ids.any? + scope = scope.where("#{Member.table_name}.id IN (SELECT DISTINCT member_id FROM #{MemberRole.table_name} WHERE role_id IN (?))", role_ids) + end + end + scope.sorted.collect {|u| [u.to_s, u.id.to_s]} + else + [] + end + end + + def before_custom_field_save(custom_field) + super + if custom_field.user_role.is_a?(Array) + custom_field.user_role.map!(&:to_s).reject!(&:blank?) + end + end + end + + class VersionFormat < RecordList + add 'version' + self.form_partial = 'custom_fields/formats/version' + field_attributes :version_status + + def possible_values_options(custom_field, object=nil) + if object.is_a?(Array) + projects = object.map {|o| o.respond_to?(:project) ? o.project : nil}.compact.uniq + projects.map {|project| possible_values_options(custom_field, project)}.reduce(:&) || [] + elsif object.respond_to?(:project) && object.project + scope = object.project.shared_versions + if custom_field.version_status.is_a?(Array) + statuses = custom_field.version_status.map(&:to_s).reject(&:blank?) + if statuses.any? + scope = scope.where(:status => statuses.map(&:to_s)) + end + end + scope.sort.collect {|u| [u.to_s, u.id.to_s]} + else + [] + end + end + + def before_custom_field_save(custom_field) + super + if custom_field.version_status.is_a?(Array) + custom_field.version_status.map!(&:to_s).reject!(&:blank?) + end + end + end + end +end diff --git a/lib/redmine/helpers/time_report.rb b/lib/redmine/helpers/time_report.rb index 09093dc95..a52181063 100644 --- a/lib/redmine/helpers/time_report.rb +++ b/lib/redmine/helpers/time_report.rb @@ -138,9 +138,10 @@ module Redmine # Add list and boolean custom fields as available criteria custom_fields.select {|cf| %w(list bool).include? cf.field_format }.each do |cf| - @available_criteria["cf_#{cf.id}"] = {:sql => "#{cf.join_alias}.value", + @available_criteria["cf_#{cf.id}"] = {:sql => cf.group_statement, :joins => cf.join_for_order_statement, :format => cf.field_format, + :custom_field => cf, :label => cf.name} end diff --git a/lib/redmine/views/labelled_form_builder.rb b/lib/redmine/views/labelled_form_builder.rb index 2bba17faf..f2c12ec95 100644 --- a/lib/redmine/views/labelled_form_builder.rb +++ b/lib/redmine/views/labelled_form_builder.rb @@ -20,7 +20,7 @@ require 'action_view/helpers/form_helper' class Redmine::Views::LabelledFormBuilder < ActionView::Helpers::FormBuilder include Redmine::I18n - (field_helpers.map(&:to_s) - %w(radio_button hidden_field fields_for) + + (field_helpers.map(&:to_s) - %w(radio_button hidden_field fields_for check_box) + %w(date_select)).each do |selector| src = <<-END_SRC def #{selector}(field, options = {}) @@ -30,6 +30,10 @@ class Redmine::Views::LabelledFormBuilder < ActionView::Helpers::FormBuilder class_eval src, __FILE__, __LINE__ end + def check_box(field, options={}, checked_value="1", unchecked_value="0") + label_for_field(field, options) + super(field, options.except(:label), checked_value, unchecked_value).html_safe + end + def select(field, choices, options = {}, html_options = {}) label_for_field(field, options) + super(field, choices, options, html_options.except(:label)).html_safe end diff --git a/public/javascripts/application.js b/public/javascripts/application.js index 255886731..a6d15f2f0 100644 --- a/public/javascripts/application.js +++ b/public/javascripts/application.js @@ -588,6 +588,20 @@ function blockEventPropagation(event) { event.preventDefault(); } +function toggleDisabledOnChange() { + var checked = $(this).is(':checked'); + $($(this).data('disables')).attr('disabled', checked); + $($(this).data('enables')).attr('disabled', !checked); +} +function toggleDisabledInit() { + $('input[data-disables], input[data-enables]').each(toggleDisabledOnChange); +} +$(document).ready(function(){ + $('#content').on('change', 'input[data-disables], input[data-enables]', toggleDisabledOnChange); + toggleDisabledInit(); +}); + $(document).ready(setupAjaxIndicator); $(document).ready(hideOnLoad); $(document).ready(addFormObserversForDoubleSubmit); + diff --git a/public/stylesheets/application.css b/public/stylesheets/application.css index 717984084..b6a9e4711 100644 --- a/public/stylesheets/application.css +++ b/public/stylesheets/application.css @@ -457,8 +457,8 @@ table.fields_permissions select {font-size:90%} table.fields_permissions td.readonly {background:#ddd;} table.fields_permissions td.required {background:#d88;} -textarea#custom_field_possible_values {width: 99%} -textarea#custom_field_default_value {width: 99%} +textarea#custom_field_possible_values {width: 95%; resize:vertical} +textarea#custom_field_default_value {width: 95%; resize:vertical} input#content_comments {width: 99%} @@ -475,6 +475,10 @@ p.pagination {margin-top:8px; font-size: 90%} html>body .tabular p {overflow:hidden;} +.tabular input, .tabular select {max-width:95%} +.tabular textarea {width:95%; resize:vertical;} +.tabular span[title] {border-bottom:1px dotted #aaa;} + .tabular label{ font-weight: bold; float: left; @@ -532,6 +536,27 @@ fieldset#notified_events .parent { padding-left: 20px; } span.required {color: #bb0000;} .summary {font-style: italic;} +.check_box_group { + display:block; + width:95%; + max-height:300px; + overflow-y:auto; + padding:2px 4px 4px 2px; + background:#fff; + border:1px solid #9EB1C2; + border-radius:2px +} +.check_box_group label { + font-weight: normal; + margin-left: 0px !important; + text-align: left; + float: none; + display: block; + width: auto; +} +.check_box_group.bool_cf {border:0; background:inherit;} +.check_box_group.bool_cf label {display: inline;} + #attachments_fields input.description {margin-left:4px; width:340px;} #attachments_fields span {display:block; white-space:nowrap;} #attachments_fields input.filename {border:0; height:1.8em; width:250px; color:#555; background-color:inherit; background:url(../images/attachment.png) no-repeat 1px 50%; padding-left:18px;} @@ -560,7 +585,9 @@ a.atom { background: url(../images/feed.png) no-repeat 1px 50%; padding: 2px 0px em.info {font-style:normal;font-size:90%;color:#888;display:block;} em.info.error {padding-left:20px; background:url(../images/exclamation.png) no-repeat 0 50%;} -textarea.text_cf {width:90%;} +textarea.text_cf {width:95%; resize:vertical;} +input.string_cf, input.link_cf {width:95%;} +select.bool_cf {width:auto !important;} #tab-content-modules fieldset p {margin:3px 0 4px 0;} diff --git a/test/functional/custom_fields_controller_test.rb b/test/functional/custom_fields_controller_test.rb index 1a91fc306..5e6833ece 100644 --- a/test/functional/custom_fields_controller_test.rb +++ b/test/functional/custom_fields_controller_test.rb @@ -30,19 +30,28 @@ class CustomFieldsControllerTest < ActionController::TestCase assert_template 'index' end - def test_new + def test_new_should_work_for_each_customized_class_and_format custom_field_classes.each do |klass| - get :new, :type => klass.name - assert_response :success - assert_template 'new' - assert_kind_of klass, assigns(:custom_field) - assert_select 'form#custom_field_form' do - assert_select 'select#custom_field_field_format[name=?]', 'custom_field[field_format]' - assert_select 'input[type=hidden][name=type][value=?]', klass.name + Redmine::FieldFormat.available_formats.each do |format_name| + get :new, :type => klass.name, :custom_field => {:field_format => format_name} + assert_response :success + assert_template 'new' + assert_kind_of klass, assigns(:custom_field) + assert_equal format_name, assigns(:custom_field).format.name + assert_select 'form#custom_field_form' do + assert_select 'select#custom_field_field_format[name=?]', 'custom_field[field_format]' + assert_select 'input[type=hidden][name=type][value=?]', klass.name + end end end end + def test_new_should_have_string_default_format + get :new, :type => 'IssueCustomField' + assert_response :success + assert_equal 'string', assigns(:custom_field).format.name + end + def test_new_issue_custom_field get :new, :type => 'IssueCustomField' assert_response :success @@ -83,7 +92,9 @@ class CustomFieldsControllerTest < ActionController::TestCase def test_default_value_should_be_a_checkbox_for_bool_custom_field get :new, :type => 'IssueCustomField', :custom_field => {:field_format => 'bool'} assert_response :success - assert_select 'input[name=?][type=checkbox]', 'custom_field[default_value]' + assert_select 'select[name=?]', 'custom_field[default_value]' do + assert_select 'option', 3 + end end def test_default_value_should_not_be_present_for_user_custom_field diff --git a/test/functional/issues_controller_test.rb b/test/functional/issues_controller_test.rb index 6fa4253f9..0431bb198 100644 --- a/test/functional/issues_controller_test.rb +++ b/test/functional/issues_controller_test.rb @@ -1361,8 +1361,10 @@ class IssuesControllerTest < ActionController::TestCase get :show, :id => 1 assert_response :success - # TODO: should display links - assert_select 'td', :text => 'Dave Lopper, John Smith' + assert_select "td.cf_#{field.id}", :text => 'Dave Lopper, John Smith' do + assert_select 'a', :text => 'Dave Lopper' + assert_select 'a', :text => 'John Smith' + end end def test_show_should_display_private_notes_with_permission_only diff --git a/test/unit/custom_field_test.rb b/test/unit/custom_field_test.rb index b99fb4353..0da6f8ba8 100644 --- a/test/unit/custom_field_test.rb +++ b/test/unit/custom_field_test.rb @@ -63,12 +63,12 @@ class CustomFieldTest < ActiveSupport::TestCase end def test_field_format_validation_should_accept_formats_added_at_runtime - Redmine::CustomFieldFormat.register 'foobar' + Redmine::FieldFormat.add 'foobar', Class.new(Redmine::FieldFormat::Base) field = CustomField.new(:name => 'Some Custom Field', :field_format => 'foobar') assert field.valid?, 'field should be valid' ensure - Redmine::CustomFieldFormat.delete 'foobar' + Redmine::FieldFormat.delete 'foobar' end def test_should_not_change_field_format_of_existing_custom_field @@ -293,4 +293,18 @@ class CustomFieldTest < ActiveSupport::TestCase assert_equal [fields[0]], CustomField.visible(User.anonymous).order("id").to_a end + + def test_float_cast_blank_value_should_return_nil + field = CustomField.new(:field_format => 'float') + assert_equal nil, field.cast_value(nil) + assert_equal nil, field.cast_value('') + end + + def test_float_cast_valid_value_should_return_float + field = CustomField.new(:field_format => 'float') + assert_equal 12.0, field.cast_value('12') + assert_equal 12.5, field.cast_value('12.5') + assert_equal 12.5, field.cast_value('+12.5') + assert_equal -12.5, field.cast_value('-12.5') + end end diff --git a/test/unit/custom_field_user_format_test.rb b/test/unit/custom_field_user_format_test.rb index 489769011..48c724936 100644 --- a/test/unit/custom_field_user_format_test.rb +++ b/test/unit/custom_field_user_format_test.rb @@ -24,23 +24,6 @@ class CustomFieldUserFormatTest < ActiveSupport::TestCase @field = IssueCustomField.create!(:name => 'Tester', :field_format => 'user') end - def test_possible_values_with_no_arguments - assert_equal [], @field.possible_values - assert_equal [], @field.possible_values(nil) - end - - def test_possible_values_with_project_resource - project = Project.find(1) - possible_values = @field.possible_values(project.issues.first) - assert possible_values.any? - assert_equal project.users.sort.collect(&:id).map(&:to_s), possible_values - end - - def test_possible_values_with_nil_project_resource - project = Project.find(1) - assert_equal [], @field.possible_values(Issue.new) - end - def test_possible_values_options_with_no_arguments assert_equal [], @field.possible_values_options assert_equal [], @field.possible_values_options(nil) diff --git a/test/unit/custom_field_version_format_test.rb b/test/unit/custom_field_version_format_test.rb index a4a790c12..d96294abc 100644 --- a/test/unit/custom_field_version_format_test.rb +++ b/test/unit/custom_field_version_format_test.rb @@ -24,22 +24,6 @@ class CustomFieldVersionFormatTest < ActiveSupport::TestCase @field = IssueCustomField.create!(:name => 'Tester', :field_format => 'version') end - def test_possible_values_with_no_arguments - assert_equal [], @field.possible_values - assert_equal [], @field.possible_values(nil) - end - - def test_possible_values_with_project_resource - project = Project.find(1) - possible_values = @field.possible_values(project.issues.first) - assert possible_values.any? - assert_equal project.shared_versions.sort.collect(&:id).map(&:to_s), possible_values - end - - def test_possible_values_with_nil_project_resource - assert_equal [], @field.possible_values(Issue.new) - end - def test_possible_values_options_with_no_arguments assert_equal [], @field.possible_values_options assert_equal [], @field.possible_values_options(nil) diff --git a/test/unit/helpers/custom_fields_helper_test.rb b/test/unit/helpers/custom_fields_helper_test.rb index 0c1081e94..6fd6f94f5 100644 --- a/test/unit/helpers/custom_fields_helper_test.rb +++ b/test/unit/helpers/custom_fields_helper_test.rb @@ -18,14 +18,15 @@ require File.expand_path('../../../test_helper', __FILE__) class CustomFieldsHelperTest < ActionView::TestCase + include ApplicationHelper include CustomFieldsHelper include Redmine::I18n include ERB::Util def test_format_boolean_value I18n.locale = 'en' - assert_equal 'Yes', format_value('1', 'bool') - assert_equal 'No', format_value('0', 'bool') + assert_equal 'Yes', format_value('1', CustomField.new(:field_format => 'bool')) + assert_equal 'No', format_value('0', CustomField.new(:field_format => 'bool')) end def test_unknow_field_format_should_be_edited_as_string diff --git a/test/unit/lib/redmine/field_format/field_format_test.rb b/test/unit/lib/redmine/field_format/field_format_test.rb new file mode 100644 index 000000000..8c8136694 --- /dev/null +++ b/test/unit/lib/redmine/field_format/field_format_test.rb @@ -0,0 +1,55 @@ +# Redmine - project management software +# Copyright (C) 2006-2013 Jean-Philippe Lang +# +# This program is free software; you can redistribute it and/or +# modify it under the terms of the GNU General Public License +# as published by the Free Software Foundation; either version 2 +# of the License, or (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software +# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + +require File.expand_path('../../../../../test_helper', __FILE__) +require 'redmine/field_format' + +class Redmine::FieldFormatTest < ActionView::TestCase + include ApplicationHelper + + def test_string_field_with_text_formatting_disabled_should_not_format_text + field = IssueCustomField.new(:field_format => 'string') + custom_value = CustomValue.new(:custom_field => field, :customized => Issue.new, :value => "*foo*") + + assert_equal "*foo*", field.format.formatted_custom_value(self, custom_value, false) + assert_equal "*foo*", field.format.formatted_custom_value(self, custom_value, true) + end + + def test_string_field_with_text_formatting_enabled_should_format_text + field = IssueCustomField.new(:field_format => 'string', :text_formatting => 'full') + custom_value = CustomValue.new(:custom_field => field, :customized => Issue.new, :value => "*foo*") + + assert_equal "*foo*", field.format.formatted_custom_value(self, custom_value, false) + assert_include "foo", field.format.formatted_custom_value(self, custom_value, true) + end + + def test_text_field_with_text_formatting_disabled_should_not_format_text + field = IssueCustomField.new(:field_format => 'text') + custom_value = CustomValue.new(:custom_field => field, :customized => Issue.new, :value => "*foo*\nbar") + + assert_equal "*foo*\nbar", field.format.formatted_custom_value(self, custom_value, false) + assert_include "*foo*\n
bar", field.format.formatted_custom_value(self, custom_value, true) + end + + def test_text_field_with_text_formatting_enabled_should_format_text + field = IssueCustomField.new(:field_format => 'text', :text_formatting => 'full') + custom_value = CustomValue.new(:custom_field => field, :customized => Issue.new, :value => "*foo*\nbar") + + assert_equal "*foo*\nbar", field.format.formatted_custom_value(self, custom_value, false) + assert_include "foo", field.format.formatted_custom_value(self, custom_value, true) + end +end diff --git a/test/unit/lib/redmine/field_format/link_format_test.rb b/test/unit/lib/redmine/field_format/link_format_test.rb new file mode 100644 index 000000000..648141282 --- /dev/null +++ b/test/unit/lib/redmine/field_format/link_format_test.rb @@ -0,0 +1,79 @@ +# Redmine - project management software +# Copyright (C) 2006-2013 Jean-Philippe Lang +# +# This program is free software; you can redistribute it and/or +# modify it under the terms of the GNU General Public License +# as published by the Free Software Foundation; either version 2 +# of the License, or (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software +# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + +require File.expand_path('../../../../../test_helper', __FILE__) +require 'redmine/field_format' + +class Redmine::LinkFieldFormatTest < ActionView::TestCase + include ApplicationHelper + + def test_link_field_should_substitute_value + field = IssueCustomField.new(:field_format => 'link', :url_pattern => 'http://foo/%value%') + custom_value = CustomValue.new(:custom_field => field, :customized => Issue.new, :value => "bar") + + assert_equal "bar", field.format.formatted_custom_value(self, custom_value, false) + assert_equal 'bar', field.format.formatted_custom_value(self, custom_value, true) + end + + def test_link_field_should_substitue_object_id_in_url + object = Issue.new + object.stubs(:id).returns(10) + + field = IssueCustomField.new(:field_format => 'link', :url_pattern => 'http://foo/%id%') + custom_value = CustomValue.new(:custom_field => field, :customized => object, :value => "bar") + + assert_equal "bar", field.format.formatted_custom_value(self, custom_value, false) + assert_equal 'bar', field.format.formatted_custom_value(self, custom_value, true) + end + + def test_link_field_should_substitue_project_id_in_url + project = Project.new + project.stubs(:id).returns(52) + object = Issue.new + object.stubs(:project).returns(project) + + field = IssueCustomField.new(:field_format => 'link', :url_pattern => 'http://foo/%project_id%') + custom_value = CustomValue.new(:custom_field => field, :customized => object, :value => "bar") + + assert_equal "bar", field.format.formatted_custom_value(self, custom_value, false) + assert_equal 'bar', field.format.formatted_custom_value(self, custom_value, true) + end + + def test_link_field_should_substitue_regexp_groups + field = IssueCustomField.new(:field_format => 'link', :regexp => /^(.+)-(.+)$/, :url_pattern => 'http://foo/%m2%/%m1%') + custom_value = CustomValue.new(:custom_field => field, :customized => Issue.new, :value => "56-142") + + assert_equal "56-142", field.format.formatted_custom_value(self, custom_value, false) + assert_equal '56-142', field.format.formatted_custom_value(self, custom_value, true) + end + + def test_link_field_without_url_pattern_should_link_to_value + field = IssueCustomField.new(:field_format => 'link') + custom_value = CustomValue.new(:custom_field => field, :customized => Issue.new, :value => "http://foo/bar") + + assert_equal "http://foo/bar", field.format.formatted_custom_value(self, custom_value, false) + assert_equal 'http://foo/bar', field.format.formatted_custom_value(self, custom_value, true) + end + + def test_link_field_without_url_pattern_should_link_to_value_with_http_by_default + field = IssueCustomField.new(:field_format => 'link') + custom_value = CustomValue.new(:custom_field => field, :customized => Issue.new, :value => "foo.bar") + + assert_equal "foo.bar", field.format.formatted_custom_value(self, custom_value, false) + assert_equal 'foo.bar', field.format.formatted_custom_value(self, custom_value, true) + end +end diff --git a/test/unit/lib/redmine/field_format/list_format_test.rb b/test/unit/lib/redmine/field_format/list_format_test.rb new file mode 100644 index 000000000..738b27302 --- /dev/null +++ b/test/unit/lib/redmine/field_format/list_format_test.rb @@ -0,0 +1,135 @@ +# Redmine - project management software +# Copyright (C) 2006-2013 Jean-Philippe Lang +# +# This program is free software; you can redistribute it and/or +# modify it under the terms of the GNU General Public License +# as published by the Free Software Foundation; either version 2 +# of the License, or (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software +# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + +require File.expand_path('../../../../../test_helper', __FILE__) +require 'redmine/field_format' + +class Redmine::ListFieldFormatTest < ActionView::TestCase + include ApplicationHelper + include Redmine::I18n + + def setup + set_language_if_valid 'en' + end + + def test_possible_existing_value_should_be_valid + field = GroupCustomField.create!(:name => 'List', :field_format => 'list', :possible_values => ['Foo', 'Bar']) + group = Group.new(:name => 'Group') + group.custom_field_values = {field.id => 'Baz'} + assert group.save(:validate => false) + + group = Group.order('id DESC').first + assert_equal ['Foo', 'Bar', 'Baz'], field.possible_custom_value_options(group.custom_value_for(field)) + assert group.valid? + end + + def test_edit_tag_should_have_id_and_name + field = IssueCustomField.new(:field_format => 'list', :possible_values => ['Foo', 'Bar'], :is_required => false) + value = CustomFieldValue.new(:custom_field => field, :customized => Issue.new) + + tag = field.format.edit_tag(self, 'abc', 'xyz', value) + assert_select_in tag, 'select[id=abc][name=xyz]' + end + + def test_edit_tag_should_contain_possible_values + field = IssueCustomField.new(:field_format => 'list', :possible_values => ['Foo', 'Bar'], :is_required => false) + value = CustomFieldValue.new(:custom_field => field, :customized => Issue.new) + + tag = field.format.edit_tag(self, 'id', 'name', value) + assert_select_in tag, 'select' do + assert_select 'option', 3 + assert_select 'option[value=]' + assert_select 'option[value=Foo]', :text => 'Foo' + assert_select 'option[value=Bar]', :text => 'Bar' + end + end + + def test_edit_tag_should_select_current_value + field = IssueCustomField.new(:field_format => 'list', :possible_values => ['Foo', 'Bar'], :is_required => false) + value = CustomFieldValue.new(:custom_field => field, :customized => Issue.new, :value => 'Bar') + + tag = field.format.edit_tag(self, 'id', 'name', value) + assert_select_in tag, 'select' do + assert_select 'option[selected=selected]', 1 + assert_select 'option[value=Bar][selected=selected]', :text => 'Bar' + end + end + + def test_edit_tag_with_multiple_should_select_current_values + field = IssueCustomField.new(:field_format => 'list', :possible_values => ['Foo', 'Bar', 'Baz'], :is_required => false, + :multiple => true) + value = CustomFieldValue.new(:custom_field => field, :customized => Issue.new, :value => ['Bar', 'Baz']) + + tag = field.format.edit_tag(self, 'id', 'name', value) + assert_select_in tag, 'select[multiple=multiple]' do + assert_select 'option[selected=selected]', 2 + assert_select 'option[value=Bar][selected=selected]', :text => 'Bar' + assert_select 'option[value=Baz][selected=selected]', :text => 'Baz' + end + end + + def test_edit_tag_with_check_box_style_should_contain_possible_values + field = IssueCustomField.new(:field_format => 'list', :possible_values => ['Foo', 'Bar'], :is_required => false, + :edit_tag_style => 'check_box') + value = CustomFieldValue.new(:custom_field => field, :customized => Issue.new) + + tag = field.format.edit_tag(self, 'id', 'name', value) + assert_select_in tag, 'span' do + assert_select 'input[type=radio]', 3 + assert_select 'label', :text => '(none)' do + assert_select 'input[value=]' + end + assert_select 'label', :text => 'Foo' do + assert_select 'input[value=Foo]' + end + assert_select 'label', :text => 'Bar' do + assert_select 'input[value=Bar]' + end + end + end + + def test_edit_tag_with_check_box_style_should_select_current_value + field = IssueCustomField.new(:field_format => 'list', :possible_values => ['Foo', 'Bar'], :is_required => false, + :edit_tag_style => 'check_box') + value = CustomFieldValue.new(:custom_field => field, :customized => Issue.new, :value => 'Bar') + + tag = field.format.edit_tag(self, 'id', 'name', value) + assert_select_in tag, 'span' do + assert_select 'input[type=radio][checked=checked]', 1 + assert_select 'label', :text => 'Bar' do + assert_select 'input[value=Bar][checked=checked]' + end + end + end + + def test_edit_tag_with_check_box_style_and_multiple_should_select_current_values + field = IssueCustomField.new(:field_format => 'list', :possible_values => ['Foo', 'Bar', 'Baz'], :is_required => false, + :multiple => true, :edit_tag_style => 'check_box') + value = CustomFieldValue.new(:custom_field => field, :customized => Issue.new, :value => ['Bar', 'Baz']) + + tag = field.format.edit_tag(self, 'id', 'name', value) + assert_select_in tag, 'span' do + assert_select 'input[type=checkbox][checked=checked]', 2 + assert_select 'label', :text => 'Bar' do + assert_select 'input[value=Bar][checked=checked]' + end + assert_select 'label', :text => 'Baz' do + assert_select 'input[value=Baz][checked=checked]' + end + end + end +end diff --git a/test/unit/lib/redmine/field_format/user_field_format_test.rb b/test/unit/lib/redmine/field_format/user_field_format_test.rb new file mode 100644 index 000000000..7cd28836b --- /dev/null +++ b/test/unit/lib/redmine/field_format/user_field_format_test.rb @@ -0,0 +1,60 @@ +# Redmine - project management software +# Copyright (C) 2006-2013 Jean-Philippe Lang +# +# This program is free software; you can redistribute it and/or +# modify it under the terms of the GNU General Public License +# as published by the Free Software Foundation; either version 2 +# of the License, or (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software +# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + +require File.expand_path('../../../../../test_helper', __FILE__) +require 'redmine/field_format' + +class Redmine::UserFieldFormatTest < ActionView::TestCase + include ApplicationHelper + + fixtures :projects, :roles, :users, :members, :member_roles + + def test_user_role_should_reject_blank_values + field = IssueCustomField.new(:name => 'Foo', :field_format => 'user', :user_role => ["1", ""]) + field.save! + assert_equal ["1"], field.user_role + end + + def test_existing_values_should_be_valid + field = IssueCustomField.create!(:name => 'Foo', :field_format => 'user', :is_for_all => true, :trackers => Tracker.all) + project = Project.generate! + user = User.generate! + User.add_to_project(user, project, Role.find_by_name('Manager')) + issue = Issue.generate!(:project_id => project.id, :tracker_id => 1, :custom_field_values => {field.id => user.id}) + + field.user_role = [Role.find_by_name('Developer').id] + field.save! + + issue = Issue.order('id DESC').first + assert_include [user.name, user.id.to_s], field.possible_custom_value_options(issue.custom_value_for(field)) + assert issue.valid? + end + + def test_possible_values_options_should_return_project_members + field = IssueCustomField.new(:field_format => 'user') + project = Project.find(1) + + assert_equal ['Dave Lopper', 'John Smith'], field.possible_values_options(project).map(&:first) + end + + def test_possible_values_options_should_return_project_members_with_selected_role + field = IssueCustomField.new(:field_format => 'user', :user_role => ["2"]) + project = Project.find(1) + + assert_equal ['Dave Lopper'], field.possible_values_options(project).map(&:first) + end +end diff --git a/test/unit/lib/redmine/field_format/version_field_format_test.rb b/test/unit/lib/redmine/field_format/version_field_format_test.rb new file mode 100644 index 000000000..e6d98e7ba --- /dev/null +++ b/test/unit/lib/redmine/field_format/version_field_format_test.rb @@ -0,0 +1,61 @@ +# Redmine - project management software +# Copyright (C) 2006-2013 Jean-Philippe Lang +# +# This program is free software; you can redistribute it and/or +# modify it under the terms of the GNU General Public License +# as published by the Free Software Foundation; either version 2 +# of the License, or (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software +# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + +require File.expand_path('../../../../../test_helper', __FILE__) +require 'redmine/field_format' + +class Redmine::VersionFieldFormatTest < ActionView::TestCase + include ApplicationHelper + + fixtures :projects, :versions, :trackers + + def test_version_status_should_reject_blank_values + field = IssueCustomField.new(:name => 'Foo', :field_format => 'version', :version_status => ["open", ""]) + field.save! + assert_equal ["open"], field.version_status + end + + def test_existing_values_should_be_valid + field = IssueCustomField.create!(:name => 'Foo', :field_format => 'version', :is_for_all => true, :trackers => Tracker.all) + project = Project.generate! + version = Version.generate!(:project => project, :status => 'open') + issue = Issue.generate!(:project_id => project.id, :tracker_id => 1, :custom_field_values => {field.id => version.id}) + + field.version_status = ["open"] + field.save! + + issue = Issue.order('id DESC').first + assert_include [version.name, version.id.to_s], field.possible_custom_value_options(issue.custom_value_for(field)) + assert issue.valid? + end + + def test_possible_values_options_should_return_project_versions + field = IssueCustomField.new(:field_format => 'version') + project = Project.find(1) + expected = project.shared_versions.sort.map(&:name) + + assert_equal expected, field.possible_values_options(project).map(&:first) + end + + def test_possible_values_options_should_return_project_versions_with_selected_status + field = IssueCustomField.new(:field_format => 'version', :version_status => ["open"]) + project = Project.find(1) + expected = project.shared_versions.sort.select {|v| v.status == "open"}.map(&:name) + + assert_equal expected, field.possible_values_options(project).map(&:first) + end +end