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

413 lines
14 KiB

#-- encoding: UTF-8
#-- copyright
# OpenProject is an open source project management software.
# Copyright (C) 2012-2021 the OpenProject GmbH
#
# 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-2013 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',
'empty' => '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
NAMESPACE_MAP = {
'user' => ['users', 'groups', 'placeholder_users'],
'version' => 'versions',
'list' => 'custom_options'
}.freeze
REPRESENTER_MAP = {
'user' => '::API::V3::Principals::PrincipalRepresenterFactory',
'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: resource_type(custom_field),
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)
@class.schema_with_allowed_link property_name(custom_field.id),
type: resource_type(custom_field),
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)
@class.schema_with_allowed_collection(
property_name(custom_field.id),
type: resource_type(custom_field),
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, writable: true)
@class.schema property_name(custom_field.id),
type: resource_type(custom_field),
name_source: ->(*) { custom_field.name },
required: custom_field.is_required,
has_default: custom_field.default_value.present?,
writable: writable,
min_length: cf_min_length(custom_field),
max_length: cf_max_length(custom_field),
regular_expression: cf_regexp(custom_field),
options: cf_options(custom_field)
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 = LinkValueGetter.link_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_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)
representer_class = derive_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
representer_class
.create(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 fragment && custom_field.field_format == 'text'
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['raw']
else
fragment
end
send(:"custom_field_#{custom_field.id}=", value)
}
end
def allowed_users_href_callback
static_filters = allowed_users_static_filters
instance_filters = method(:allowed_users_instance_filter)
->(*) {
# Careful to not alter the static_filters object here.
# It is made available in the closure (which is class level) and would thus
# keep the appended filters between requests.
filters = static_filters + instance_filters.call(represented)
api_v3_paths.path_for(:principals, filters: filters, page_size: 0)
}
end
def cf_min_length(custom_field)
custom_field.min_length if custom_field.min_length.positive?
end
def cf_max_length(custom_field)
custom_field.max_length if custom_field.max_length.positive?
end
def cf_regexp(custom_field)
custom_field.regexp unless custom_field.regexp.blank?
end
def cf_options(custom_field)
{
rtl: ("true" if custom_field.content_right_to_left)
}
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 derive_representer_class(custom_field)
REPRESENTER_MAP[custom_field.field_format]
.constantize
end
def resource_type(custom_field)
type = TYPE_MAP[custom_field.field_format]
if custom_field.multi_value?
"[]#{type}"
else
type
end
end
def allowed_users_static_filters
[
{ status: { operator: '!',
values: [Principal.statuses[:locked].to_s] } },
{ type: { operator: '=',
values: %w[User Group PlaceholderUser] } }
]
end
def allowed_users_instance_filter(represented)
project_id_value =
if represented.respond_to?(:model) && represented.model.is_a?(Project)
represented.id
else
represented.project_id.to_s
end
if project_id_value.present?
[{ member: { operator: '=', values: [project_id_value.to_s] } }]
else
[{ member: { operator: '*', values: [] } }]
end
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
Fix/update wysiwyg styles (#8844) This is a refactoring of the CSS classes in the WYSIWYG editor. The classes now use proper BEM and are almost completely independent of other CSS. It also includes small style refactorings, like a reduction of heading size in attribute fields, and an increase in heading size in all other instances. * Initial class definitions * Added more classes * Added Table of Contents basics * CkEditor applying custom CSS classes to p, h1, h2, h3, h4, h5, h6, li and blockquote * CKEditorInspector removed * op css class for headings * op css class for paragraphs * op css class for code/code block * adapt specs to altered markdown/html generation * adapt grid/budget representers to altered signature * op css class for lists * op css class for toc * op css class for links * Start working on typography css * op css class for tables * Fixing more typography, trying out larger headers * Applying custom classes to li, a, blockquote, figure, table, tr, td, th, image, codeblock, figcaption and macros * adapt specs to altered link classes * op css class for images * apply user content container class throughout application * CSS alignment custom classes applied to table * op css class for task list checkbox * Added task checkbox class * amend list checkbox class in backend * op css class for table thead element * adapt specs on image html generation * Updated table and typography styles * Update typography and figure styles * Figure overflow handling * Table alignment styles + ckEditor styles removed * rename wiki-anchor to op-uc-link_permalink * wrap table in div as well as figure * Updated code-block * Update permalinks * Fixed a lot about tables * Removed Description header from work-packages page * Fix frontend styles * Add placeholder styling, fix toc * Fixed figure print * working with table aligns * Custom class add to task lists * Custom classes applied to theads * op-uc-container custom class added to container * Codeblocks inside pre elements * Fix: single <code> and <a> tags * explicitly require overwritten gem class Apparently, the gem is not loaded yet when it is registered as a filter when in eager loading mode * adapt spec expectation to altered toc rendering * CkInspector removed * Latest ckeditor changes * remove highlight css class from wiki content * allow html pipleline to handle macros with additional classes * Fixed a lot of print css for tables * Add general print css back in * Update Table of Contents styling * Custom classes on ul, ol, li and task-lists * Revert "Custom classes on ul, ol, li and task-lists" This reverts commit 0d27d281378b324330ea2f25632de898269e2122. * Custom classes on ul, ol, li and task-lists * Custom classes on column's th * remove placeholder class when rendering * WOrking on task lists * Changing task-list classes, changed tests * Updated list styles * Remove unused todo list styles * remove checked in binstubs * Fix table of contents * adapt todo list handing in backend pipeline * adapt specs to altered css classes * Add numbers to table of contents * Better comments in table of contents * Fix: wrap single <table> with a <figure> * Fixes to todo list design * Updated todo list scss to fix nested lists * adapt selectors in table spec * Update table styles * Improve table borders more * Custom classes specs * Fix: no need to remove regular list classes when its type changes * Add modifier for inline headings * Update table editing styles * Remove break-word tests * wrap images just like tables * Update figure content styles * Fix: All tests passing (ul.op-uc-list_task-list) * div.op-uc-figure--content wrapping tables * Specs for figures wrappers div.op-uc-figure--content * Fix: add custom classes to links and codes again * Table wrapper div reverted + specs * Fix inline palceholders * Custom macro type classes * Add basic macro placeholder changes * Move heading permalink after text * Fix word-break spec * Sending figure styles to the backend (width) * extend test to take ckeditor placeholder into account * avoid adding bem classes multiple times * attempt to fix flickering spec * Removing image spinner when uploading finishes * adapt spec expectations Co-authored-by: Aleix Suau <info@macrofonoestudio.es> Co-authored-by: ulferts <jens.ulferts@googlemail.com>
4 years ago
def create(represented, **args)
create_class(represented, args[:current_user])
.new(represented, **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