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/app/services/projects/copy_service.rb

134 lines
4.7 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 COPYRIGHT and LICENSE files for more details.
#++
module Projects
class CopyService < ::BaseServices::Copy
include Projects::Concerns::NewProjectService
[34444] Projects copy APIv3 (#9149) * Create copy project endpoint * Add representers * Add _meta representer for copy module information * Add Meta payload representer * Extract parsing of copy attributes into service * Extract enqueue job for projects copy * Keep request object available in the bodied endpoint this allows us to access grape (e.g., for redirecting) * Add DelayedModify endpoint that redirects to job status * Use DelayedModify endpoint for copying projects * Add api paths for form/copy * Disable cache on ProjectCopyPayload * Add spec * Add resource spec * Extend schema for meta * Extend docs * Don't pass service result, but state as meta to forms * Use copy dependencies for naming copy options in API * Add description property for counting * Remove unused action attribute * Skip writable checks on meta property for payloads * Use prepend to allow create(...) usage with meta * Extend copy spec with custom fields usage * Add spec for copy flags * Add todos * Pass errors correctly to copy settings * Remove invalid parameters to copy that are now caught through project service * Remove duplicated validation * Linting * Make count a human readable, formattable description string * Make source count string readable * Provide the source project for generating the counts * Extract copying of attachments into sepearate dependent services This will allow the API to dynamically generate a copy association schema from each dependent service * Add spec for copy schema representer * Add payload representer spec * Also validate the model to pass the validations when copying * Make description optional and add note to schemas.apib * Add send_notifications to representer * Allow to configure sendNotifications * Allow bodied to receive a state process callback That allows us to manage the meta state on the API level, not on the service level * Make other services compatible with BaseCallable * Fix params passing from BaseCallable Wrapping a single hash into kwargs obviously loses their key indifference and we can't expect all services to use a single params object. Older services use kwargs * Copy wiki page with parent_id This will save some memory instead of memoizing the entire wiki page * Fix typo * Default to true for all copy associations That means if only a true value is passed, all other options will still be true * Do not try to copy attachments if the base dependency wasnt copied * Ensure null identifier gets rendered * Fix paths to the form and commit * Change redirect to an URL * Extend documentation on meta properties as table * Ensure we pass a default params if incoming params are nil Now that SetAttributes needs to splat params, they do no longer correctly get the no-param-default behavior of Ruby, so we need to explictly assign a default params hash * Fix expect for trailing path
4 years ago
def self.copy_dependencies
[
::Projects::Copy::MembersDependentService,
::Projects::Copy::VersionsDependentService,
::Projects::Copy::CategoriesDependentService,
::Projects::Copy::WorkPackagesDependentService,
::Projects::Copy::WorkPackageAttachmentsDependentService,
::Projects::Copy::WikiDependentService,
::Projects::Copy::WikiPageAttachmentsDependentService,
::Projects::Copy::ForumsDependentService,
::Projects::Copy::QueriesDependentService,
::Projects::Copy::BoardsDependentService,
::Projects::Copy::OverviewDependentService
]
end
##
# In case a rollback is needed,
# destroy the copied project again.
def rollback
state.project&.destroy
end
protected
##
# Whether to skip the given key.
# Useful when copying nested dependencies
def skip_dependency?(params, dependency_cls)
!Copy::Dependency.should_copy?(params, dependency_cls.identifier.to_sym)
end
def initialize_copy(source, params)
target = Project.new
[37026] Add new project form with template selection (#9193) * Projects form working with formly 50% * Removed console.log * Working with formattable * Working with formattable * Input with id and label * Input with id and label * Useless dependencies removed * Saving forms + required labels with * * First backend validation approach * Removed reload on type change + keep model on route changes * Handlig backend validations with setError * Formatting the form model to submit * Make up refactor * working with op-form-field * Form creation moved to the service * Working with op-form-field wrapper * Working with validation and op-form-field * Working with []CustomFields * Clean up * Clean up * Clean up * Clean up * Form routing working * Notification on form error and success * Refactor + removed useless dynamic form observable * DynamicFieldsService with tests * Refactor: inputs catalog + catch form load error * Filter out non writable fields * Refactor: naming consistency * Cleaning comments * dynamic-fields-service tests + wrapper component * DynamicForm Tests * @ngx-formly/core dependency added * Cleaning up * Provide DynamicFieldsService in root so it can be used independently * DynamicForm working as a FormControl * Getting route params sync * Global FormsService: submit + formatting + error handling * Fix: @Optional() FormGroupDirective in OpFormFieldComponent * Code climate fix * Removed CdkTextareaAutosize because of CDK issue 22469 * DynamicFormComponent tests * Dynamic input test helpers + boolean and text tests * Refactor edit fields to avoid circular dependencies in the dynamic forms * Naming fix * IntegerInputComponent tests * SelectInputComponent tests * Fix: duplicated identifier on inputs * Extract toolbar to be reused for now Still TBD whether we want to move them right now to the frontend? * Create new project route and redirect to rails view after saving * fieldsSettingsPipe + hide 'identifier' on projects * Handling multi-values (also as links) and passwords * Some TODOs removed * FormattableTextareaInputComponent tests * Projects form working with formly 50% * Removed console.log * Working with formattable * Working with formattable * Input with id and label * Input with id and label * Useless dependencies removed * Saving forms + required labels with * * First backend validation approach * Removed reload on type change + keep model on route changes * Handlig backend validations with setError * Formatting the form model to submit * Make up refactor * working with op-form-field * Form creation moved to the service * Working with op-form-field wrapper * Working with validation and op-form-field * Working with []CustomFields * Clean up * Clean up * Clean up * Clean up * Form routing working * Notification on form error and success * Refactor + removed useless dynamic form observable * DynamicFieldsService with tests * Refactor: inputs catalog + catch form load error * Filter out non writable fields * Refactor: naming consistency * Cleaning comments * dynamic-fields-service tests + wrapper component * DynamicForm Tests * @ngx-formly/core dependency added * Cleaning up * DynamicForm working as a FormControl * Getting route params sync * Global FormsService: submit + formatting + error handling * Fix: @Optional() FormGroupDirective in OpFormFieldComponent * Code climate fix * Removed CdkTextareaAutosize because of CDK issue 22469 * DynamicFormComponent tests * Dynamic input test helpers + boolean and text tests * Refactor edit fields to avoid circular dependencies in the dynamic forms * Naming fix * IntegerInputComponent tests * SelectInputComponent tests * Fix: duplicated identifier on inputs * Extract toolbar to be reused for now Still TBD whether we want to move them right now to the frontend? * Create new project route and redirect to rails view after saving * fieldsSettingsPipe + hide 'identifier' on projects * Handling multi-values (also as links) and passwords * Some TODOs removed * FormattableTextareaInputComponent tests * _isResourceSchema based on parent?.location * Scope DynamicFieldsService to DynamicFormComponent * Added backend validation method to FormsService * Remove form from DynamicForm when not isStandaloneForm * Allow multiple form keys to validate * Remove form from non standalone forms * Remove duplicated button * Fix: dynamic form with ng-template not showing validations * DynamicForm programatic validation * Add new project component that posts to the copy form * Hide the submit button input * Unify ckeditor spacings with other dynamic-form elements * Basic fixes to invalid dynamic form fields * Load the templated projects with newly added action * Fix invalid styles for dynamic inputs * Updates to form styles, add op-form and op-fieldset * Soften inputs to 2px * Update input styles globally * Redirect to job status modal when response is job status * fix: load projects routes * Collapsible groups working * Fix: setTimeout datepicker to wait DOM ready * resourceId added to project settings form * fieldsLayoutConfig * formUrl & formHttpMethod @Inputs * Avoid replacing non ending '/form' strings * formUrl @Input * @Input model * identifier hidden * Populate the model * Add new project component * Tests removed * Show create message when creating new resource * Change location to rails * Add field_name helper for testing * Add form field helper classes and fix tests * Remove templated from copy for now * Fix more tests * Reset toolbar from dev * Skip identifier test * Set overflow to visible when expanded * Fix more tests * Rename data-field-name to data-qa-field-name * Review feedback * Uncollapse group fields when they contains errors * Fix text spec * Remove instantiate template service * Remove unnecessary ProjectController#create Co-authored-by: Aleix Suau <info@macrofonoestudio.es> Co-authored-by: Benjamin Bädorf <b.baedorf@openproject.com>
4 years ago
target.attributes = source.attributes.dup.except(*skipped_attributes)
# Clear enabled modules
target.enabled_modules = []
target.enabled_module_names = source.enabled_module_names - %w[repository]
target.types = source.types
target.work_package_custom_fields = source.work_package_custom_fields
# Copy status object
target.status = source.status&.dup
# Take over the CF values for attributes
target.custom_field_values = source.custom_value_attributes
# Additional input target params
target_project_params = params[:target_project_params].with_indifferent_access
cleanup_target_project_params(source, target, target_project_params)
cleanup_target_project_attributes(source, target, target_project_params)
# Assign additional params from user
call = Projects::SetAttributesService
.new(user: user,
model: target,
contract_class: Projects::CopyContract,
[34444] Projects copy APIv3 (#9149) * Create copy project endpoint * Add representers * Add _meta representer for copy module information * Add Meta payload representer * Extract parsing of copy attributes into service * Extract enqueue job for projects copy * Keep request object available in the bodied endpoint this allows us to access grape (e.g., for redirecting) * Add DelayedModify endpoint that redirects to job status * Use DelayedModify endpoint for copying projects * Add api paths for form/copy * Disable cache on ProjectCopyPayload * Add spec * Add resource spec * Extend schema for meta * Extend docs * Don't pass service result, but state as meta to forms * Use copy dependencies for naming copy options in API * Add description property for counting * Remove unused action attribute * Skip writable checks on meta property for payloads * Use prepend to allow create(...) usage with meta * Extend copy spec with custom fields usage * Add spec for copy flags * Add todos * Pass errors correctly to copy settings * Remove invalid parameters to copy that are now caught through project service * Remove duplicated validation * Linting * Make count a human readable, formattable description string * Make source count string readable * Provide the source project for generating the counts * Extract copying of attachments into sepearate dependent services This will allow the API to dynamically generate a copy association schema from each dependent service * Add spec for copy schema representer * Add payload representer spec * Also validate the model to pass the validations when copying * Make description optional and add note to schemas.apib * Add send_notifications to representer * Allow to configure sendNotifications * Allow bodied to receive a state process callback That allows us to manage the meta state on the API level, not on the service level * Make other services compatible with BaseCallable * Fix params passing from BaseCallable Wrapping a single hash into kwargs obviously loses their key indifference and we can't expect all services to use a single params object. Older services use kwargs * Copy wiki page with parent_id This will save some memory instead of memoizing the entire wiki page * Fix typo * Default to true for all copy associations That means if only a true value is passed, all other options will still be true * Do not try to copy attachments if the base dependency wasnt copied * Ensure null identifier gets rendered * Fix paths to the form and commit * Change redirect to an URL * Extend documentation on meta properties as table * Ensure we pass a default params if incoming params are nil Now that SetAttributes needs to splat params, they do no longer correctly get the no-param-default behavior of Ruby, so we need to explictly assign a default params hash * Fix expect for trailing path
4 years ago
contract_options: { copy_source: source, validate_model: true })
.with_state(state)
.call(target_project_params)
# Retain values after the set attributes service
retain_attributes(source, target, target_project_params)
# Retain the project in the state for other dependent
# copy services to use
state.project = target
call
end
def retain_attributes(source, target, target_project_params)
# Ensure we keep the public value of the source project
# which might get overridden by the SetAttributesService
# unless the user provided a different value
target.public = source.public unless target_project_params.key?(:public)
end
def cleanup_target_project_params(_source, _target, target_project_params)
if (parent_id = target_project_params[:parent_id]) && (parent = Project.find_by(id: parent_id)) && !user.allowed_to?(
:add_subprojects, parent
)
target_project_params.delete(:parent_id)
end
end
def cleanup_target_project_attributes(_source, target, _target_project_params)
if target.parent && !user.allowed_to?(:add_subprojects, target.parent)
target.parent = nil
end
end
def skipped_attributes
[37026] Add new project form with template selection (#9193) * Projects form working with formly 50% * Removed console.log * Working with formattable * Working with formattable * Input with id and label * Input with id and label * Useless dependencies removed * Saving forms + required labels with * * First backend validation approach * Removed reload on type change + keep model on route changes * Handlig backend validations with setError * Formatting the form model to submit * Make up refactor * working with op-form-field * Form creation moved to the service * Working with op-form-field wrapper * Working with validation and op-form-field * Working with []CustomFields * Clean up * Clean up * Clean up * Clean up * Form routing working * Notification on form error and success * Refactor + removed useless dynamic form observable * DynamicFieldsService with tests * Refactor: inputs catalog + catch form load error * Filter out non writable fields * Refactor: naming consistency * Cleaning comments * dynamic-fields-service tests + wrapper component * DynamicForm Tests * @ngx-formly/core dependency added * Cleaning up * Provide DynamicFieldsService in root so it can be used independently * DynamicForm working as a FormControl * Getting route params sync * Global FormsService: submit + formatting + error handling * Fix: @Optional() FormGroupDirective in OpFormFieldComponent * Code climate fix * Removed CdkTextareaAutosize because of CDK issue 22469 * DynamicFormComponent tests * Dynamic input test helpers + boolean and text tests * Refactor edit fields to avoid circular dependencies in the dynamic forms * Naming fix * IntegerInputComponent tests * SelectInputComponent tests * Fix: duplicated identifier on inputs * Extract toolbar to be reused for now Still TBD whether we want to move them right now to the frontend? * Create new project route and redirect to rails view after saving * fieldsSettingsPipe + hide 'identifier' on projects * Handling multi-values (also as links) and passwords * Some TODOs removed * FormattableTextareaInputComponent tests * Projects form working with formly 50% * Removed console.log * Working with formattable * Working with formattable * Input with id and label * Input with id and label * Useless dependencies removed * Saving forms + required labels with * * First backend validation approach * Removed reload on type change + keep model on route changes * Handlig backend validations with setError * Formatting the form model to submit * Make up refactor * working with op-form-field * Form creation moved to the service * Working with op-form-field wrapper * Working with validation and op-form-field * Working with []CustomFields * Clean up * Clean up * Clean up * Clean up * Form routing working * Notification on form error and success * Refactor + removed useless dynamic form observable * DynamicFieldsService with tests * Refactor: inputs catalog + catch form load error * Filter out non writable fields * Refactor: naming consistency * Cleaning comments * dynamic-fields-service tests + wrapper component * DynamicForm Tests * @ngx-formly/core dependency added * Cleaning up * DynamicForm working as a FormControl * Getting route params sync * Global FormsService: submit + formatting + error handling * Fix: @Optional() FormGroupDirective in OpFormFieldComponent * Code climate fix * Removed CdkTextareaAutosize because of CDK issue 22469 * DynamicFormComponent tests * Dynamic input test helpers + boolean and text tests * Refactor edit fields to avoid circular dependencies in the dynamic forms * Naming fix * IntegerInputComponent tests * SelectInputComponent tests * Fix: duplicated identifier on inputs * Extract toolbar to be reused for now Still TBD whether we want to move them right now to the frontend? * Create new project route and redirect to rails view after saving * fieldsSettingsPipe + hide 'identifier' on projects * Handling multi-values (also as links) and passwords * Some TODOs removed * FormattableTextareaInputComponent tests * _isResourceSchema based on parent?.location * Scope DynamicFieldsService to DynamicFormComponent * Added backend validation method to FormsService * Remove form from DynamicForm when not isStandaloneForm * Allow multiple form keys to validate * Remove form from non standalone forms * Remove duplicated button * Fix: dynamic form with ng-template not showing validations * DynamicForm programatic validation * Add new project component that posts to the copy form * Hide the submit button input * Unify ckeditor spacings with other dynamic-form elements * Basic fixes to invalid dynamic form fields * Load the templated projects with newly added action * Fix invalid styles for dynamic inputs * Updates to form styles, add op-form and op-fieldset * Soften inputs to 2px * Update input styles globally * Redirect to job status modal when response is job status * fix: load projects routes * Collapsible groups working * Fix: setTimeout datepicker to wait DOM ready * resourceId added to project settings form * fieldsLayoutConfig * formUrl & formHttpMethod @Inputs * Avoid replacing non ending '/form' strings * formUrl @Input * @Input model * identifier hidden * Populate the model * Add new project component * Tests removed * Show create message when creating new resource * Change location to rails * Add field_name helper for testing * Add form field helper classes and fix tests * Remove templated from copy for now * Fix more tests * Reset toolbar from dev * Skip identifier test * Set overflow to visible when expanded * Fix more tests * Rename data-field-name to data-qa-field-name * Review feedback * Uncollapse group fields when they contains errors * Fix text spec * Remove instantiate template service * Remove unnecessary ProjectController#create Co-authored-by: Aleix Suau <info@macrofonoestudio.es> Co-authored-by: Benjamin Bädorf <b.baedorf@openproject.com>
4 years ago
%w[id created_at updated_at name identifier active templated lft rgt]
end
end
end