OpenProject is the leading open source project management software for product, project and portfolio management. A powerful Jira alternative with agile planning, issue tracking, roadmaps, Gantt charts, time tracking, collaboration features, and more. Available on premises or in the cloud. ⭐ Star us on GitHub
Ruby agile-developmentangularbcfboardsbug-trackerganttgantt-chartifcissue-trackerjira-alternativekanbanopenprojectproduct-managementproject-managementproject-planningroadmaprubyscrumtimelineworkflows
[#58520] Implement fetching tree structure
Eric Schuberta8c0ec5b4344
diff --git a/app/models/queries/custom_fields/hierarchy/item_query.rb b/app/models/queries/custom_fields/hierarchy/item_query.rbnew file mode 100644index 00000000000..a1bd47a6ece--- /dev/null+++ b/app/models/queries/custom_fields/hierarchy/item_query.rb@@ -0,0 +1,42 @@+#-- copyright+# OpenProject is an open source project management software.+# Copyright (C) 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 COPYRIGHT and LICENSE files for more details.+#++++module Queries+ module CustomFields+ module Hierarchy+ class ItemQuery+ include ::Queries::BaseQuery+ include ::Queries::UnpersistedQuery++ def self.model+ CustomField::Hierarchy::Item+ end+ end+ end+ end+enddiff --git a/app/services/custom_fields/hierarchy/hierarchical_item_service.rb b/app/services/custom_fields/hierarchy/hierarchical_item_service.rbindex e0274491d14..49b5f882da1 100644--- a/app/services/custom_fields/hierarchy/hierarchical_item_service.rb+++ b/app/services/custom_fields/hierarchy/hierarchical_item_service.rb@@ -112,11 +112,23 @@ module CustomFieldsSuccess()end- def soft_delete_item(item)+ def soft_delete_item(item:)# Soft delete the item and childrenraise NotImplementedErrorend+ def hashed_subtree(item:, depth:)+ if depth >= 0+ Success(item.hash_tree(limit_depth: depth + 1))+ else+ Success(item.hash_tree)+ end+ end++ def descendant_of?(item:, parent:)+ item.descendant_of?(parent) ? Success() : Failure()+ end+privatedef create_root_item(custom_field)diff --git a/config/locales/en.yml b/config/locales/en.ymlindex d59da529359..b7e8e4d47ff 100644--- a/config/locales/en.yml+++ b/config/locales/en.yml@@ -295,12 +295,19 @@ en:dry_validation:errors:+ integer?: "must be an integer"+ filled?: "must be filled"+ greater_or_equal_zero: "must be greater or equal to 0"+ not_found: "not found"rules:label:- filled?: "must be filled"not_unique: "must be unique within the same hierarchy level"+ parent:+ not_descendant: "must be a descendant of the hierarchy root"rules:label: "Label"+ parent: "Parent"+ depth: "Depth"global_search:placeholder: "Search in %{app_title}"@@ -1591,7 +1598,7 @@ en:create_new_page: "Wiki page"date:- abbr_day_names: ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"]+ abbr_day_names: [ "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" ]abbr_month_names:[~,diff --git a/docs/api/apiv3/components/examples/hierarchy_item_collection_filtered_response.yml b/docs/api/apiv3/components/examples/hierarchy_item_collection_filtered_response.ymlindex b1a4a45f7ec..f56cebe3018 100644--- a/docs/api/apiv3/components/examples/hierarchy_item_collection_filtered_response.yml+++ b/docs/api/apiv3/components/examples/hierarchy_item_collection_filtered_response.yml@@ -10,43 +10,52 @@ value:id: 1338label: Stormtroopersshort: ST+ depth: 1_links:self:- href: /api/v3/custom_field/42/items/1338+ href: /api/v3/custom_field_items/1338+ name: Stormtroopersparent:- href: /api/v3/custom_field/42/items/1337+ href: /api/v3/custom_field_items/1337+ name: nullchildren:- - href: /api/v3/custom_field/42/items/1340+ - href: /api/v3/custom_field_items/1340name: ST-377- - href: /api/v3/custom_field/42/items/1341+ - href: /api/v3/custom_field_items/1341name: ST-422- _type: HierarchyItemid: 1340label: ST-377short: null+ depth: 2_links:self:- href: /api/v3/custom_field/42/items/1340+ href: /api/v3/custom_field_items/1340+ name: ST-377parent:- href: /api/v3/custom_field/42/items/1338+ href: /api/v3/custom_field_items/1338+ name: Stormtrooperschildren:- - href: /api/v3/custom_field/42/items/1480+ - href: /api/v3/custom_field_items/1480name: ST-377-200- - href: /api/v3/custom_field/42/items/1481+ - href: /api/v3/custom_field_items/1481name: ST-377-201- _type: HierarchyItemid: 1341label: ST-422short: null+ depth: 2_links:self:- href: /api/v3/custom_field/42/items/1341+ href: /api/v3/custom_field_items/1341+ name: ST-422parent:- href: /api/v3/custom_field/42/items/1338+ href: /api/v3/custom_field_items/1338+ name: Stormtrooperschildren:- - href: /api/v3/custom_field/42/items/1580+ - href: /api/v3/custom_field_items/1580name: ST-422-137- - href: /api/v3/custom_field/42/items/1581+ - href: /api/v3/custom_field_items/1581name: ST-422-138_links:self:diff --git a/docs/api/apiv3/components/examples/hierarchy_item_collection_response.yml b/docs/api/apiv3/components/examples/hierarchy_item_collection_response.ymlindex ac6a9683d3c..0fd692dd746 100644--- a/docs/api/apiv3/components/examples/hierarchy_item_collection_response.yml+++ b/docs/api/apiv3/components/examples/hierarchy_item_collection_response.yml@@ -10,35 +10,41 @@ value:id: 1337label: nullshort: null+ depth: 0_links:self:- href: /api/v3/custom_field/42/items/1337+ href: /api/v3/custom_field_items/1337+ name: nullparent:href: nullchildren:- - href: /api/v3/custom_field/42/items/1338+ - href: /api/v3/custom_field_items/1338name: Stormtroopers- - href: /api/v3/custom_field/42/items/1339+ - href: /api/v3/custom_field_items/1339name: Dark Troopers- _type: HierarchyItemid: 1338label: Stormtroopersshort: ST+ depth: 1_links:self:- href: /api/v3/custom_field/42/items/1338+ href: /api/v3/custom_field_items/1338+ name: Stormtroopersparent:- href: /api/v3/custom_field/42/items/1337+ href: /api/v3/custom_field_items/1337+ name: nullchildren:- - href: /api/v3/custom_field/42/items/1340+ - href: /api/v3/custom_field_items/1340name: ST-377- - href: /api/v3/custom_field/42/items/1341+ - href: /api/v3/custom_field_items/1341name: ST-422- _type: HierarchyItem_hint: hierarchy item shortened for brevityid: 1340label: ST-377short: null+ depth: 2- _hint: hierarchy item shortened for brevity_links:self:diff --git a/docs/api/apiv3/components/examples/hierarchy_item_response.yml b/docs/api/apiv3/components/examples/hierarchy_item_response.ymlnew file mode 100644index 00000000000..17568d048ca--- /dev/null+++ b/docs/api/apiv3/components/examples/hierarchy_item_response.yml@@ -0,0 +1,20 @@+description: |-+ Simple response of a single item of a custom field of type hierarchy.+value:+ _type: HierarchyItem+ id: 1338+ label: Stormtroopers+ short: ST+ depth: 1+ _links:+ self:+ href: /api/v3/custom_field_items/1338+ name: Stormtroopers+ parent:+ href: /api/v3/custom_field_items/1337+ name: null+ children:+ - href: /api/v3/custom_field_items/1340+ name: ST-377+ - href: /api/v3/custom_field_items/1341+ name: ST-422diff --git a/docs/api/apiv3/components/schemas/hierarchy_item_read_model.yml b/docs/api/apiv3/components/schemas/hierarchy_item_read_model.ymlindex 302c21756e8..6b427cddf87 100644--- a/docs/api/apiv3/components/schemas/hierarchy_item_read_model.yml+++ b/docs/api/apiv3/components/schemas/hierarchy_item_read_model.yml@@ -15,6 +15,9 @@ properties:short:type: stringdescription: The short name of the hierarchy item+ depth:+ type: integer+ description: The hierarchy depth. The root item has a depth of 0._links:type: objectproperties:diff --git a/docs/api/apiv3/openapi-spec.yml b/docs/api/apiv3/openapi-spec.ymlindex 1865613e785..8b08defb710 100644--- a/docs/api/apiv3/openapi-spec.yml+++ b/docs/api/apiv3/openapi-spec.yml@@ -188,6 +188,8 @@ paths:"$ref": "./paths/custom_action_execute.yml""/api/v3/custom_fields/{id}/items":"$ref": "./paths/custom_field_items.yml"+ "/api/v3/custom_field_items/{id}":+ "$ref": "./paths/custom_field_item.yml""/api/v3/custom_options/{id}":"$ref": "./paths/custom_option.yml""/api/v3/days/non_working":@@ -495,6 +497,8 @@ components:$ref: "./components/examples/hierarchy_item_collection_filtered_response.yml"HierarchyItemCollectionResponse:$ref: "./components/examples/hierarchy_item_collection_response.yml"+ HierarchyItemResponse:+ $ref: "./components/examples/hierarchy_item_response.yml"MembershipCreateRequestCustomMessage:$ref: "./components/examples/membership-create-request-custom-message.yml"MembershipCreateRequestGlobalRole:@@ -956,4 +960,4 @@ tags:- "$ref": "./tags/work_packages.yml"- "$ref": "./tags/work_schedule.yml"security:- - BasicAuth: [ ]+ - BasicAuth: []diff --git a/docs/api/apiv3/paths/custom_field_item.yml b/docs/api/apiv3/paths/custom_field_item.ymlnew file mode 100644index 00000000000..c1ac90dda38--- /dev/null+++ b/docs/api/apiv3/paths/custom_field_item.yml@@ -0,0 +1,49 @@+# /api/v3/custom_field_items/{id}+---+get:+ summary: Get a custom field hierarchy item+ operationId: get_custom_field_item+ description: |-+ Retrieves a single custom field item specified by its unique identifier.+ parameters:+ - name: id+ description: The custom field item's unique identifier+ in: path+ example: '42'+ required: true+ schema:+ type: integer+ responses:+ '200':+ description: OK+ content:+ application/hal+json:+ schema:+ $ref: '../components/schemas/hierarchy_item_read_model.yml'+ examples:+ 'simple response':+ $ref: '../components/examples/hierarchy_item_response.yml'+ '403':+ description: Returned if the user is not logged in.+ content:+ application/hal+json:+ schema:+ $ref: '../components/schemas/error_response.yml'+ examples:+ response:+ value:+ _type: Error+ errorIdentifier: urn:openproject-org:api:v3:errors:MissingPermission+ message: You are not authorized to access this resource.+ '404':+ description: Returned if the custom field item does not exist or the user is not logged in.+ content:+ application/hal+json:+ schema:+ $ref: '../components/schemas/error_response.yml'+ examples:+ response:+ value:+ _type: Error+ errorIdentifier: urn:openproject-org:api:v3:errors:NotFound+ message: The requested resource could not be found.diff --git a/docs/api/apiv3/paths/custom_field_items.yml b/docs/api/apiv3/paths/custom_field_items.ymlindex 4e47755bbc3..e51e9e3bffe 100644--- a/docs/api/apiv3/paths/custom_field_items.yml+++ b/docs/api/apiv3/paths/custom_field_items.yml@@ -10,6 +10,10 @@ get:has a reference to its parent and children. The list is ordered in a depth-first manner. The first item is therequested parent. If parent was unset, the root item is returned as first element.+ Passing the `depth` query parameter allows to limit the depth of the hierarchy. If the depth is unset, the full+ hierarchy tree is returned. If the depth is set to `0`, only the requested parent is returned. Any other positive+ integer will return the number of children levels specified by this value.+This endpoint only returns, if the custom field is of type `hierarchy`.parameters:- name: id@@ -45,6 +49,18 @@ get:$ref: '../components/examples/hierarchy_item_collection_response.yml''filtered response':$ref: '../components/examples/hierarchy_item_collection_filtered_response.yml'+ '403':+ description: Returned if the user is not logged in.+ content:+ application/hal+json:+ schema:+ $ref: '../components/schemas/error_response.yml'+ examples:+ response:+ value:+ _type: Error+ errorIdentifier: urn:openproject-org:api:v3:errors:MissingPermission+ message: You are not authorized to access this resource.'404':description: Returned if the custom field does not exist.content:diff --git a/lib/api/errors/unprocessable_content.rb b/lib/api/errors/unprocessable_content.rbindex 95537b8bd73..2b2eaf5c4e9 100644--- a/lib/api/errors/unprocessable_content.rb+++ b/lib/api/errors/unprocessable_content.rb@@ -31,13 +31,6 @@ module APIclass UnprocessableContent < ErrorBaseidentifier "UnprocessableContent"code 422-- def initialize(property, message)- super(message)-- @property = property- @details = { attribute: property }- endendendenddiff --git a/lib/api/v3/custom_fields/custom_fields_api.rb b/lib/api/v3/custom_fields/custom_fields_api.rbnew file mode 100644index 00000000000..a8332356928--- /dev/null+++ b/lib/api/v3/custom_fields/custom_fields_api.rb@@ -0,0 +1,47 @@+#-- copyright+# OpenProject is an open source project management software.+# Copyright (C) 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 COPYRIGHT and LICENSE files for more details.+#++++module API+ module V3+ module CustomFields+ class CustomFieldsAPI < ::API::OpenProjectAPI+ resource :custom_fields do+ route_param :id, type: Integer, desc: "Custom Field ID" do+ after_validation do+ authorize_logged_in++ @custom_field = CustomField.find(params[:id])+ end++ mount API::V3::CustomFields::Hierarchy::ItemsAPI+ end+ end+ end+ end+ end+enddiff --git a/lib/api/v3/custom_fields/hierarchy/get_items_parameter_contract.rb b/lib/api/v3/custom_fields/hierarchy/get_items_parameter_contract.rbnew file mode 100644index 00000000000..3f7f1bab1fb--- /dev/null+++ b/lib/api/v3/custom_fields/hierarchy/get_items_parameter_contract.rb@@ -0,0 +1,72 @@+# frozen_string_literal: true++#-- copyright+# OpenProject is an open source project management software.+# Copyright (C) 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 COPYRIGHT and LICENSE files for more details.+#++++module API+ module V3+ module CustomFields+ module Hierarchy+ class GetItemsParameterContract < Dry::Validation::Contract+ config.messages.backend = :i18n++ option :hierarchy_root++ params do+ optional(:parent).filled(:integer)+ optional(:depth).filled(:integer)+ end++ rule(:parent) do+ next unless key?++ parent_item = ::CustomField::Hierarchy::Item.find_by(id: value)++ if parent_item.nil?+ key.failure(:not_found)+ elsif persistence_service.descendant_of?(item: parent_item, parent: hierarchy_root).failure?+ key.failure(:not_descendant)+ end+ end++ rule(:depth) do+ next unless key?++ key.failure(:greater_or_equal_zero) if value < 0+ end++ private++ def persistence_service+ @persistence_service ||= ::CustomFields::Hierarchy::HierarchicalItemService.new+ end+ end+ end+ end+ end+enddiff --git a/lib/api/v3/custom_fields/hierarchy/hierarchy_item_collection_representer.rb b/lib/api/v3/custom_fields/hierarchy/hierarchy_item_collection_representer.rbnew file mode 100644index 00000000000..badb8cad2e7--- /dev/null+++ b/lib/api/v3/custom_fields/hierarchy/hierarchy_item_collection_representer.rb@@ -0,0 +1,38 @@+#-- copyright+# OpenProject is an open source project management software.+# Copyright (C) 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 COPYRIGHT and LICENSE files for more details.+#++++module API+ module V3+ module CustomFields+ module Hierarchy+ class HierarchyItemCollectionRepresenter < ::API::Decorators::UnpaginatedCollection+ end+ end+ end+ end+enddiff --git a/lib/api/v3/custom_fields/hierarchy/hierarchy_item_representer.rb b/lib/api/v3/custom_fields/hierarchy/hierarchy_item_representer.rbindex bf1c63b26e2..fddbbd2a3f4 100644--- a/lib/api/v3/custom_fields/hierarchy/hierarchy_item_representer.rb+++ b/lib/api/v3/custom_fields/hierarchy/hierarchy_item_representer.rb@@ -35,7 +35,36 @@ module API"HierarchyItem"end+ self_link path: :custom_field_item,+ title_getter: ->(*) { represented.label }+property :id++ property :label, render_nil: true++ property :short, render_nil: true++ property :depth++ link :parent do+ next if represented.root?++ parent = represented.parent++ {+ href: api_v3_paths.custom_field_item(parent.id),+ title: parent.label+ }+ end++ links :children do+ represented.children.map do |child|+ {+ href: api_v3_paths.custom_field_item(child.id),+ title: child.label+ }+ end+ endendendenddiff --git a/lib/api/v3/custom_fields/hierarchy/item_api.rb b/lib/api/v3/custom_fields/hierarchy/item_api.rbnew file mode 100644index 00000000000..d0ce2d51b6a--- /dev/null+++ b/lib/api/v3/custom_fields/hierarchy/item_api.rb@@ -0,0 +1,53 @@+#-- copyright+# OpenProject is an open source project management software.+# Copyright (C) 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 COPYRIGHT and LICENSE files for more details.+#++++module API+ module V3+ module CustomFields+ module Hierarchy+ class ItemAPI < ::API::OpenProjectAPI+ resource :custom_field_items do+ route_param :id, type: Integer, desc: "Custom Field Item ID" do+ after_validation do+ authorize_logged_in++ @custom_field_item = CustomField::Hierarchy::Item.find(params[:id])+ end++ get &::API::V3::Utilities::Endpoints::Show+ .new(model: CustomField::Hierarchy::Item,+ render_representer: HierarchyItemRepresenter,+ instance_generator: ->(*) { @custom_field_item })+ .mount+ end+ end+ end+ end+ end+ end+enddiff --git a/lib/api/v3/custom_fields/hierarchy/items_api.rb b/lib/api/v3/custom_fields/hierarchy/items_api.rbnew file mode 100644index 00000000000..101e6fca600--- /dev/null+++ b/lib/api/v3/custom_fields/hierarchy/items_api.rb@@ -0,0 +1,131 @@+#-- copyright+# OpenProject is an open source project management software.+# Copyright (C) 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 COPYRIGHT and LICENSE files for more details.+#++++module API+ module V3+ module CustomFields+ module Hierarchy+ class ItemsAPI < ::API::OpenProjectAPI+ include Dry::Monads[:result]++ helpers do+ def flatten_tree_hash(hash)+ flat_list = []+ queue = [hash]++ # From the service we get a hashed tree like this:+ # {:a => {:b => {:c1 => {:d1 => {}}, :c2 => {:d2 => {}}}, :b2 => {}}}+ # We flatten it depth first to this result list:+ # [:a, :b, :c1, :d1, :c2, :d2, :b2]++ while queue.any?+ current = queue.shift+ item, children = current.shift+ flat_list << item+ queue.unshift(current) unless current.empty?+ queue.unshift(children) unless children.empty?+ end++ flat_list+ end++ def item_list(query)+ hierarchy_root = get_hierarchy_root(query)++ validation = GetItemsParameterContract.new(hierarchy_root:).call(params)+ handle_validation_errors(validation) if validation.failure?++ start_item = ::CustomField::Hierarchy::Item.find_by(id: validation[:parent]) || hierarchy_root+ depth = validation[:depth] || -1++ flat_tree(start_item, depth)+ end++ def flat_tree(item, depth)+ sub_tree = ::CustomFields::Hierarchy::HierarchicalItemService+ .new+ .hashed_subtree(item:, depth:)+ .either(+ ->(value) { value },+ ->(error) do+ msg = "#{I18n.t('api_v3.errors.code_500')} #{error}"+ raise ::API::Errors::InternalError.new(msg)+ end+ )++ flatten_tree_hash(sub_tree)+ end++ def get_hierarchy_root(query)+ items = query.results.where(custom_field: @custom_field)+ if items.count != 1+ msg = "corrupt data found, invalid number of hierarchy roots for custom field"+ raise ::API::Errors::InternalError.new(msg)+ end++ items.first+ end++ def handle_validation_errors(validation)+ message = ""+ validation.errors(full: true).to_h.each_value do |value|+ message += "#{value.join(', ')}\n"+ end++ raise ::API::Errors::InvalidQuery.new(message.chomp)+ end+ end++ resource :items do+ after_validation do+ unless @custom_field.field_format_hierarchy?+ message = "Hierarchy items do only exists for custom fields of type hierarchy."+ raise ::API::Errors::UnprocessableContent.new(message)+ end+ end++ get do+ query = ParamsToQueryService.new(::CustomField::Hierarchy::Item,+ current_user,+ query_class: ::Queries::CustomFields::Hierarchy::ItemQuery)+ .call(params)++ unless query.valid?+ message = I18n.t("api_v3.errors.missing_or_malformed_parameter", parameter: "filters")+ raise ::API::Errors::InvalidQuery.new(message)+ end++ self_link = api_v3_paths.custom_field_items(@custom_field.id, params[:parent], params[:depth])+ HierarchyItemCollectionRepresenter.new(item_list(query), self_link:, current_user:)+ end+ end+ end+ end+ end+ end+enddiff --git a/lib/api/v3/root.rb b/lib/api/v3/root.rbindex d299b19fd7a..a30041f486f 100644--- a/lib/api/v3/root.rb+++ b/lib/api/v3/root.rb@@ -46,11 +46,13 @@ module APImount ::API::V3::Actions::ActionsAPImount ::API::V3::Activities::ActivitiesAPImount ::API::V3::Attachments::AttachmentsAPI- mount ::API::V3::Capabilities::CapabilitiesAPImount ::API::V3::Backups::BackupsAPI+ mount ::API::V3::Capabilities::CapabilitiesAPImount ::API::V3::Categories::CategoriesAPImount ::API::V3::Configuration::ConfigurationAPImount ::API::V3::CustomActions::CustomActionsAPI+ mount ::API::V3::CustomFields::CustomFieldsAPI+ mount ::API::V3::CustomFields::Hierarchy::ItemAPImount ::API::V3::CustomOptions::CustomOptionsAPImount ::API::V3::Days::DaysAPImount ::API::V3::Grids::GridsAPIdiff --git a/lib/api/v3/utilities/path_helper.rb b/lib/api/v3/utilities/path_helper.rbindex c3a04f70a83..1bf20c07963 100644--- a/lib/api/v3/utilities/path_helper.rb+++ b/lib/api/v3/utilities/path_helper.rb@@ -44,11 +44,13 @@ module APIRequestStore.store[:"cached_#{plural_name}"] ||= "#{root}/#{path}"endend+private_class_method :indexdef self.show(name, path = name)define_singleton_method(name) { |id| build_path(path, id) }end+private_class_method :showdef self.create_form(name)@@ -56,11 +58,13 @@ module APIRequestStore.store[:"cached_create_#{name}_form"] ||= build_path(name, "form")endend+private_class_method :create_formdef self.update_form(name)define_singleton_method(:"#{name}_form") { |id| build_path(name, id, "form") }end+private_class_method :update_formdef self.schema(name)@@ -68,11 +72,13 @@ module APIRequestStore.store[:"cached_#{name}_schema"] ||= build_path(name, "schema")endend+private_class_method :schemadef self.build_path(name, *kwargs)[root, name.to_s.pluralize, *kwargs].compact.join("/")end+private_class_method :build_pathdef self.resources(name,@@ -83,6 +89,7 @@ module APIsend(method, name)endend+private_class_method :resources# Determining the root_path on every url we want to render is@@ -200,6 +207,24 @@ module API"#{custom_action(id)}/execute"end+ def self.custom_field(id)+ "#{root}/custom_fields/#{id}"+ end++ def self.custom_field_item(id)+ "#{root}/custom_field_items/#{id}"+ end++ def self.custom_field_items(id, parent = nil, depth = nil)+ query = { parent:, depth: }.compact_blank.to_query++ if query.present?+ "#{custom_field(id)}/items?#{query}"+ else+ "#{custom_field(id)}/items"+ end+ end+def self.custom_option(id)"#{root}/custom_options/#{id}"end@@ -511,9 +536,9 @@ module APIdef self.work_package(id, timestamps: nil)"#{root}/work_packages/#{id}" + \- if (param_value = timestamps_to_param_value(timestamps)).present? && Array(timestamps).any?(&:historic?)- "?#{{ timestamps: param_value }.to_query}"- end.to_s+ if (param_value = timestamps_to_param_value(timestamps)).present? && Array(timestamps).any?(&:historic?)+ "?#{{ timestamps: param_value }.to_query}"+ end.to_senddef self.work_package_schema(project_id, type_id)diff --git a/spec/lib/api/v3/utilities/resource_link_generator_spec.rb b/spec/lib/api/v3/utilities/resource_link_generator_spec.rbindex b9c0f035527..867e0f3ae49 100644--- a/spec/lib/api/v3/utilities/resource_link_generator_spec.rb+++ b/spec/lib/api/v3/utilities/resource_link_generator_spec.rb@@ -55,7 +55,7 @@ RSpec.describe API::V3::Utilities::ResourceLinkGenerator doendit "returns nil for unsupported records" do- record = create(:custom_field)+ record = create(:oauth_client_token)expect(subject.make_link(record)).to be_nilenddiff --git a/spec/services/custom_fields/hierarchy/hierarchical_item_service_spec.rb b/spec/services/custom_fields/hierarchy/hierarchical_item_service_spec.rbindex 21f6d5d2b19..903c76fcd94 100644--- a/spec/services/custom_fields/hierarchy/hierarchical_item_service_spec.rb+++ b/spec/services/custom_fields/hierarchy/hierarchical_item_service_spec.rb@@ -178,7 +178,7 @@ RSpec.describe CustomFields::Hierarchy::HierarchicalItemService doendend- describe "reorder_item" do+ describe "#reorder_item" dolet!(:lando) { service.insert_item(parent: root, label: "lando").value! }let!(:chewbacca) { service.insert_item(parent: root, label: "AWOOO").value! }@@ -238,4 +238,26 @@ RSpec.describe CustomFields::Hierarchy::HierarchicalItemService doexpect(chewbacca.reload.sort_order).to eq(2)endend++ describe "#hashed_subtree" do+ let!(:lando) { service.insert_item(parent: root, label: "lando").value! }+ let!(:chewbacca) { service.insert_item(parent: root, label: "AWOOO").value! }+ let!(:lowbacca) { service.insert_item(parent: chewbacca, label: "ARWWWW").value! }++ it "produces a hash version of the tree" do+ subtree = service.hashed_subtree(item: root, depth: -1)++ expect(subtree.value!).to be_a(Hash)+ expect(subtree.value![root].size).to eq(3)+ expect(subtree.value![root][lando]).to be_empty+ expect(subtree.value![root][chewbacca][lowbacca]).to be_empty+ end++ it "produces a hash version of a sub tree with limited depth" do+ subtree = service.hashed_subtree(item: chewbacca, depth: 0)++ expect(subtree.value!).to be_a(Hash)+ expect(subtree.value![chewbacca]).to be_empty+ end+ endend