OpenProject is the leading open source project management software.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
openproject/lib/api/v3/utilities/custom_field_injector.rb

391 lines
13 KiB

#-- encoding: UTF-8
#-- copyright
# OpenProject is a project management system.
# Copyright (C) 2012-2018 the OpenProject Foundation (OPF)
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License version 3.
#
# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:
# Copyright (C) 2006-2017 Jean-Philippe Lang
# Copyright (C) 2010-2013 the ChiliProject Team
#
# 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.
#
# See docs/COPYRIGHT.rdoc for more details.
#++
module API
module V3
module Utilities
class CustomFieldInjector
TYPE_MAP = {
'string' => 'String',
'text' => 'Formattable',
'int' => 'Integer',
'float' => 'Float',
'date' => 'Date',
'bool' => 'Boolean',
'user' => 'User',
'version' => 'Version',
'list' => 'CustomOption'
}.freeze
LINK_FORMATS = %w(list user version).freeze
PATH_METHOD_MAP = {
'user' => :user,
'version' => :version,
'list' => :custom_option
}.freeze
NAMESPACE_MAP = {
'user' => 'users',
'version' => 'versions',
'list' => 'custom_options'
}.freeze
REPRESENTER_MAP = {
'user' => '::API::V3::Users::UserRepresenter',
'version' => '::API::V3::Versions::VersionRepresenter',
'list' => '::API::V3::CustomOptions::CustomOptionRepresenter'
}.freeze
class << self
def create_value_representer(custom_fields, representer)
new_representer_class_with(representer) do |injector|
custom_fields.each do |custom_field|
injector.inject_value(custom_field)
end
end
end
def create_schema_representer(custom_fields, representer)
new_representer_class_with(representer) do |injector|
custom_fields.each do |custom_field|
injector.inject_schema(custom_field)
end
end
end
private
def linked_field?(custom_field)
LINK_FORMATS.include?(custom_field.field_format)
end
def property_field?(custom_field)
!linked_field?(custom_field)
end
def new_representer_class_with(representer)
injector = new(representer)
yield injector
injector.modified_representer_class
end
end
def initialize(representer_class)
@class = Class.new(representer_class) do
include API::Decorators::LinkedResource
end
end
def modified_representer_class
@class
end
def inject_schema(custom_field)
case custom_field.field_format
10 years ago
when 'version'
inject_version_schema(custom_field)
10 years ago
when 'user'
inject_user_schema(custom_field)
10 years ago
when 'list'
inject_list_schema(custom_field)
10 years ago
else
inject_basic_schema(custom_field)
end
end
def inject_value(custom_field)
case custom_field.field_format
when *LINK_FORMATS
10 years ago
inject_link_value(custom_field)
else
inject_property_value(custom_field)
end
end
private
def property_name(id)
"customField#{id}".to_sym
end
def inject_version_schema(custom_field)
@class.schema_with_allowed_collection property_name(custom_field.id),
type: 'Version',
name_source: ->(*) { custom_field.name },
values_callback: ->(*) {
represented
.assignable_custom_field_values(custom_field)
},
writable: true,
value_representer: Versions::VersionRepresenter,
link_factory: ->(version) {
{
href: api_v3_paths.version(version.id),
title: version.name
}
},
required: custom_field.is_required
end
def inject_user_schema(custom_field)
type = custom_field.multi_value? ? "[]User" : "User"
@class.schema_with_allowed_link property_name(custom_field.id),
type: type,
writable: true,
name_source: ->(*) { custom_field.name },
required: custom_field.is_required,
href_callback: allowed_users_href_callback
end
def inject_list_schema(custom_field)
type = custom_field.multi_value ? "[]CustomOption" : "CustomOption"
@class.schema_with_allowed_collection(
property_name(custom_field.id),
type: type,
name_source: ->(*) { custom_field.name },
values_callback: list_schemas_values_callback(custom_field),
value_representer: CustomOptions::CustomOptionRepresenter,
writable: true,
link_factory: list_schemas_link_callback,
required: custom_field.is_required
)
end
def inject_basic_schema(custom_field)
@class.schema property_name(custom_field.id),
type: TYPE_MAP[custom_field.field_format],
name_source: ->(*) { custom_field.name },
required: custom_field.is_required,
has_default: custom_field.default_value.present?,
writable: true,
min_length: cf_min_length(custom_field),
max_length: cf_max_length(custom_field),
regular_expression: cf_regexp(custom_field)
end
def path_method_for(custom_field)
PATH_METHOD_MAP[custom_field.field_format]
end
10 years ago
def inject_link_value(custom_field)
name = property_name(custom_field.id)
expected_namespace = NAMESPACE_MAP[custom_field.field_format]
link = link_value_getter_for(custom_field, path_method_for(custom_field))
setter = link_value_setter_for(custom_field, name, expected_namespace)
getter = embedded_link_value_getter(custom_field)
method = if custom_field.multi_value?
:resources
else
:resource
end
@class.send(method,
property_name(custom_field.id),
link: link,
setter: setter,
getter: getter)
10 years ago
end
def link_value_getter_for(custom_field, path_method)
LinkValueGetter.new custom_field, path_method
10 years ago
end
def link_value_setter_for(custom_field, property, expected_namespace)
Fix/bump representable (#5465) * bump reform and roar -> bumps representer * adapt to changed validation interface * disable initializer patch for now * adapt to changed representable attr interface * can no longer have private methods inside a representer * private no longer possible for representer * bump reform * wip - restyle validation * remove commented out patch * apply injection as prescribed * reactivate reform error symbols patch * remove patch to Hash superfluous wit ruby 2.3 * remove outdated human_attribute_name patch * whitespace fixes * adapt filter name after removal of human_attribute_name patch * adapt filter specs to no longer rely on human_attribute_name patch * fix version filter name * remove reliance on no longer existing human_attribute_name patch * use correct key in journal formatter * remove private from representer * adapt to altered setter interface * reenable i18n for error messages in contracts * no private methods in representer * defined model for contracts * fix validaton * instantiate correct Object * define model for contract * circumvent now existing render method on reform * replace deprecated constant * patch correct reform class - not the module - via prepend * refactor too complex method * replace deprations * remove remnants of parentId * prevent error symbols from existing twice * adapt user representer to altered setter interface * adapt watcher representer to altered setter interface * remove now unnessary patch * adapt setter to altered interface * adapt spec * fix custom field setters * remove parentId from wp representer As the parent is a wp resource, clients should use the parent link instead * adapt spec to changed valid? interface * remove parentId from wp schema * replace references of parentId in frontend * remove TODO [ci skip]
8 years ago
->(fragment:, represented:, **) {
values = Array([fragment].flatten).flat_map do |link|
href = link['href']
value =
if href
::API::Utilities::ResourceLinkParser.parse_id(
href,
property: property,
expected_version: '3',
expected_namespace: expected_namespace
)
end
[value].compact
end
10 years ago
represented.send(:"custom_field_#{custom_field.id}=", values)
10 years ago
}
end
def embedded_link_value_getter(custom_field)
klass = representer_class(custom_field)
proc do
# Do not embed list or multi values as their links contain all the
# information needed (title and href) already.
next if !represented.available_custom_fields.include?(custom_field) ||
custom_field.list? ||
custom_field.multi_value?
value = represented.send custom_field.accessor_name
next unless value
klass
.new(value, current_user: current_user)
end
10 years ago
end
def inject_property_value(custom_field)
Fix/bump representable (#5465) * bump reform and roar -> bumps representer * adapt to changed validation interface * disable initializer patch for now * adapt to changed representable attr interface * can no longer have private methods inside a representer * private no longer possible for representer * bump reform * wip - restyle validation * remove commented out patch * apply injection as prescribed * reactivate reform error symbols patch * remove patch to Hash superfluous wit ruby 2.3 * remove outdated human_attribute_name patch * whitespace fixes * adapt filter name after removal of human_attribute_name patch * adapt filter specs to no longer rely on human_attribute_name patch * fix version filter name * remove reliance on no longer existing human_attribute_name patch * use correct key in journal formatter * remove private from representer * adapt to altered setter interface * reenable i18n for error messages in contracts * no private methods in representer * defined model for contracts * fix validaton * instantiate correct Object * define model for contract * circumvent now existing render method on reform * replace deprecated constant * patch correct reform class - not the module - via prepend * refactor too complex method * replace deprations * remove remnants of parentId * prevent error symbols from existing twice * adapt user representer to altered setter interface * adapt watcher representer to altered setter interface * remove now unnessary patch * adapt setter to altered interface * adapt spec * fix custom field setters * remove parentId from wp representer As the parent is a wp resource, clients should use the parent link instead * adapt spec to changed valid? interface * remove parentId from wp schema * replace references of parentId in frontend * remove TODO [ci skip]
8 years ago
@class.property "custom_field_#{custom_field.id}".to_sym,
as: property_name(custom_field.id),
getter: property_value_getter_for(custom_field),
setter: property_value_setter_for(custom_field),
render_nil: true
end
def property_value_getter_for(custom_field)
->(*) {
next unless available_custom_fields.include?(custom_field)
value = send custom_field.accessor_name
if custom_field.field_format == 'text'
::API::Decorators::Formattable.new(value, object: self)
else
value
end
}
end
def property_value_setter_for(custom_field)
Fix/bump representable (#5465) * bump reform and roar -> bumps representer * adapt to changed validation interface * disable initializer patch for now * adapt to changed representable attr interface * can no longer have private methods inside a representer * private no longer possible for representer * bump reform * wip - restyle validation * remove commented out patch * apply injection as prescribed * reactivate reform error symbols patch * remove patch to Hash superfluous wit ruby 2.3 * remove outdated human_attribute_name patch * whitespace fixes * adapt filter name after removal of human_attribute_name patch * adapt filter specs to no longer rely on human_attribute_name patch * fix version filter name * remove reliance on no longer existing human_attribute_name patch * use correct key in journal formatter * remove private from representer * adapt to altered setter interface * reenable i18n for error messages in contracts * no private methods in representer * defined model for contracts * fix validaton * instantiate correct Object * define model for contract * circumvent now existing render method on reform * replace deprecated constant * patch correct reform class - not the module - via prepend * refactor too complex method * replace deprations * remove remnants of parentId * prevent error symbols from existing twice * adapt user representer to altered setter interface * adapt watcher representer to altered setter interface * remove now unnessary patch * adapt setter to altered interface * adapt spec * fix custom field setters * remove parentId from wp representer As the parent is a wp resource, clients should use the parent link instead * adapt spec to changed valid? interface * remove parentId from wp schema * replace references of parentId in frontend * remove TODO [ci skip]
8 years ago
->(fragment:, **) {
value = if custom_field.field_format == 'text'
fragment['raw']
else
fragment
end
send(:"custom_field_#{custom_field.id}=", value)
}
end
def allowed_users_href_callback
# for now we ASSUME that every customized that has a
# user custom field, will also define a project...
->(*) {
params = [{ status: { operator: '!',
values: [Principal::STATUSES[:builtin].to_s,
Principal::STATUSES[:locked].to_s] } },
{ type: { operator: '=', values: ['User'] } },
{ member: { operator: '=', values: [represented.project_id.to_s] } }]
query = CGI.escape(::JSON.dump(params))
User mentions feature (#5897) * Extend syntax for linking users via their ID * Allow login names for linking user profiles. * User require_relative for legacy tests * Add specs for login name based user links; Fixes other specs, too. * Notify mentioned users * Notify linked users; - require quotes for login names in user links as login names can contain spaces, dots that are typical word boundaries - Adding specs * For the decision who gets notified due to mentions only the visibility permissions of the recipient are relevant. * Rubucop satisfaction * Add autocomplete for user names to work pack package descriptions and activity - Uses API V3 Principals endpoint. - Extends API endpoint with name filter and name order. - Make it activate when user types an "@" or a "user#" - Still for work packages only. * Directly show a list of users after typing '@' and allow navigating list with cursor keys * Add an '@' before the rendered user link * Adopting spec as WP autocompleter now expects whitespace before hash sign * Adding spec for using user autocompleter * Introduce magic pageSize of 0 for maximum length * Add id filter for principals * Allow pagination for principals and protect from falling back to a too low default value * Fixing specs * fixing typo in spec * Add magic number 0 for user custom fields * Add a toParams method for ApiV3FilterBuilder * User ApiV3FilterBuilder in path helper service * Add test for mentions principals to path helper * WIP * Convert auto complete helper to TS [ci skip]
7 years ago
"#{api_v3_paths.principals}?filters=#{query}&pageSize=0"
}
end
def cf_min_length(custom_field)
custom_field.min_length if custom_field.min_length > 0
end
def cf_max_length(custom_field)
custom_field.max_length if custom_field.max_length > 0
end
def cf_regexp(custom_field)
custom_field.regexp unless custom_field.regexp.blank?
end
def list_schemas_values_callback(custom_field)
->(*) { represented.assignable_custom_field_values(custom_field) }
end
def list_schemas_link_callback
->(value) do
{
href: api_v3_paths.custom_option(value.id),
title: value.to_s
}
end
end
def representer_class(custom_field)
REPRESENTER_MAP[custom_field.field_format]
.constantize
end
module RepresenterClass
def custom_field_injector(config)
@custom_field_injector_config = config.reverse_merge custom_field_injector_config
end
def custom_field_injector_config
@custom_field_injector_config ||= { type: :value_representer,
injector_class: ::API::V3::Utilities::CustomFieldInjector }
end
def create_class(represented, current_user)
custom_fields = if current_user.admin?
represented.available_custom_fields
else
represented.available_custom_fields.select(&:visible?)
end
custom_field_class(custom_fields)
end
def create(*args)
create_class(args.first, args.last[:current_user])
.new(*args)
end
def custom_field_class(custom_fields)
custom_field_sha = OpenProject::Cache::CacheKey.expand(custom_fields.sort_by(&:id))
cached_custom_field_classes[custom_field_sha] ||= begin
injector_class = custom_field_injector_config[:injector_class]
method_name = :"create_#{custom_field_injector_config[:type]}"
injector_class.send(method_name, custom_fields, self)
end
end
def cached_custom_field_classes
@cached_custom_field_classes ||= {}
end
end
end
end
end
end