Skip to content

EspoCRM – Open Source CRM Application

category impro dev

Yuri Kuznetsovf81d8a39d4ba
diff --git a/application/Espo/Core/Controllers/RecordTree.php b/application/Espo/Core/Controllers/RecordTree.php
index 66f267056b..69ccf73772 100644
--- a/application/Espo/Core/Controllers/RecordTree.php
+++ b/application/Espo/Core/Controllers/RecordTree.php
@@ -29,15 +29,20 @@
namespace Espo\Core\Controllers;
+use Espo\Core\Acl\Table;
use Espo\Core\Exceptions\Forbidden;
use Espo\Core\Exceptions\BadRequest;
use Espo\Core\Exceptions\Error;
use Espo\Core\Exceptions\NotFound;
use Espo\Core\ORM\Entity;
+use Espo\Core\Templates\Entities\CategoryTree;
use Espo\Services\RecordTree as Service;
use Espo\Core\Api\Request;
+use Espo\Tools\CategoryTree\Move\MoveParams;
+use Espo\Tools\CategoryTree\MoveService;
+use RuntimeException;
use stdClass;
class RecordTree extends Record
@@ -58,11 +63,6 @@ class RecordTree extends Record
*/
public function getActionListTree(Request $request): stdClass
{
- if (method_exists($this, 'actionListTree')) {
- // For backward compatibility.
- return (object) $this->actionListTree($request->getRouteParams(), $request->getParsedBody(), $request);
- }
-
$selectParams = $this->fetchSearchParamsFromRequest($request);
$parentId = $request->getQueryParam('parentId');
@@ -101,7 +101,7 @@ class RecordTree extends Record
*/
public function getActionLastChildrenIdList(Request $request): array
{
- if (!$this->acl->check($this->name, 'read')) {
+ if (!$this->acl->check($this->name, Table::ACTION_READ)) {
throw new Forbidden();
}
@@ -110,6 +110,68 @@ class RecordTree extends Record
return $this->getRecordTreeService()->getLastChildrenIdList($parentId);
}
+ /**
+ * @throws Forbidden
+ * @throws BadRequest
+ * @throws NotFound
+ * @throws Error
+ * @noinspection PhpUnused
+ */
+ public function postActionMove(Request $request): bool
+ {
+ if (!$this->acl->check($this->name, Table::ACTION_EDIT)) {
+ throw new Forbidden();
+ }
+
+ $id = $request->getParsedBody()->id ?? null;
+ $referenceId = $request->getParsedBody()->referenceId ?? null;
+ $type = $request->getParsedBody()->type ?? null;
+
+ if (!is_string($id)) {
+ throw new BadRequest("Bad id.");
+ }
+
+ if (!is_string($referenceId)) {
+ throw new BadRequest("Bad referenceId.");
+ }
+
+ $typeInternal = match ($type) {
+ 'into' => MoveParams::TYPE_INTO,
+ 'before' => MoveParams::TYPE_BEFORE,
+ 'after' => MoveParams::TYPE_AFTER,
+ default => null,
+ };
+
+ if ($typeInternal === null) {
+ throw new BadRequest("Bad type.");
+ }
+
+ $entity = $this->getRecordService()->getEntity($id);
+
+ if (!$entity) {
+ throw new NotFound("Record not found.");
+ }
+
+ if (!$entity instanceof CategoryTree) {
+ throw new RuntimeException("Non-tree entity.");
+ }
+
+ if (!$this->acl->checkEntityEdit($entity)) {
+ throw new Forbidden("No edit access.");
+ }
+
+ $params = new MoveParams(
+ type: $typeInternal,
+ referenceId: $referenceId,
+ );
+
+ $service = $this->injectableFactory->create(MoveService::class);
+
+ $service->move($entity, $params);
+
+ return true;
+ }
+
/**
* @return Service<Entity>
*/
@@ -117,7 +179,9 @@ class RecordTree extends Record
{
$service = $this->getRecordService();
- assert($service instanceof Service);
+ if (!$service instanceof Service) {
+ throw new RuntimeException();
+ }
return $service;
}
diff --git a/application/Espo/Modules/Crm/Resources/metadata/entityDefs/DocumentFolder.json b/application/Espo/Modules/Crm/Resources/metadata/entityDefs/DocumentFolder.json
index 0148939fb0..0973fc0bdb 100644
--- a/application/Espo/Modules/Crm/Resources/metadata/entityDefs/DocumentFolder.json
+++ b/application/Espo/Modules/Crm/Resources/metadata/entityDefs/DocumentFolder.json
@@ -78,7 +78,7 @@
}
},
"collection": {
- "orderBy": "parent",
+ "orderBy": "name",
"order": "asc"
},
"additionalTables": {
diff --git a/application/Espo/Modules/Crm/Resources/metadata/entityDefs/KnowledgeBaseCategory.json b/application/Espo/Modules/Crm/Resources/metadata/entityDefs/KnowledgeBaseCategory.json
index 03388e9453..a5a467e01c 100644
--- a/application/Espo/Modules/Crm/Resources/metadata/entityDefs/KnowledgeBaseCategory.json
+++ b/application/Espo/Modules/Crm/Resources/metadata/entityDefs/KnowledgeBaseCategory.json
@@ -35,6 +35,7 @@
"order": {
"type": "int",
"minValue": 1,
+ "readOnly": true,
"disableFormatting": true,
"textFilterDisabled": true
},
diff --git a/application/Espo/Modules/Crm/Resources/metadata/entityDefs/TargetListCategory.json b/application/Espo/Modules/Crm/Resources/metadata/entityDefs/TargetListCategory.json
index 3edce22786..efabe4af36 100644
--- a/application/Espo/Modules/Crm/Resources/metadata/entityDefs/TargetListCategory.json
+++ b/application/Espo/Modules/Crm/Resources/metadata/entityDefs/TargetListCategory.json
@@ -7,6 +7,7 @@
"order": {
"type": "int",
"minValue": 1,
+ "readOnly": true,
"textFilterDisabled": true
},
"description": {
diff --git a/application/Espo/Resources/metadata/entityDefs/EmailTemplateCategory.json b/application/Espo/Resources/metadata/entityDefs/EmailTemplateCategory.json
index e177cd40f3..41ab5fcdc7 100644
--- a/application/Espo/Resources/metadata/entityDefs/EmailTemplateCategory.json
+++ b/application/Espo/Resources/metadata/entityDefs/EmailTemplateCategory.json
@@ -7,6 +7,7 @@
"order": {
"type": "int",
"minValue": 1,
+ "readOnly": true,
"textFilterDisabled": true
},
"description": {
diff --git a/application/Espo/Tools/CategoryTree/Move/MoveParams.php b/application/Espo/Tools/CategoryTree/Move/MoveParams.php
new file mode 100644
index 0000000000..ae91ebbdb2
--- /dev/null
+++ b/application/Espo/Tools/CategoryTree/Move/MoveParams.php
@@ -0,0 +1,42 @@
+<?php
+/************************************************************************
+ * This file is part of EspoCRM.
+ *
+ * EspoCRM – Open Source CRM application.
+ * Copyright (C) 2014-2025 Yurii Kuznietsov, Taras Machyshyn, Oleksii Avramenko
+ * Website: https://www.espocrm.com
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as published by
+ * the Free Software Foundation, either version 3 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 Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <https://www.gnu.org/licenses/>.
+ *
+ * The interactive user interfaces in modified source and object code versions
+ * of this program must display Appropriate Legal Notices, as required under
+ * Section 5 of the GNU Affero General Public License version 3.
+ *
+ * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
+ * these Appropriate Legal Notices must retain the display of the "EspoCRM" word.
+ ************************************************************************/
+
+namespace Espo\Tools\CategoryTree\Move;
+
+readonly class MoveParams
+{
+ public const TYPE_INTO = 0;
+ public const TYPE_BEFORE = 1;
+ public const TYPE_AFTER = 2;
+
+ public function __construct(
+ public int $type,
+ public ?string $referenceId = null,
+ ) {}
+}
diff --git a/application/Espo/Tools/CategoryTree/MoveService.php b/application/Espo/Tools/CategoryTree/MoveService.php
new file mode 100644
index 0000000000..e62b36c2eb
--- /dev/null
+++ b/application/Espo/Tools/CategoryTree/MoveService.php
@@ -0,0 +1,234 @@
+<?php
+/************************************************************************
+ * This file is part of EspoCRM.
+ *
+ * EspoCRM – Open Source CRM application.
+ * Copyright (C) 2014-2025 Yurii Kuznietsov, Taras Machyshyn, Oleksii Avramenko
+ * Website: https://www.espocrm.com
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as published by
+ * the Free Software Foundation, either version 3 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 Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <https://www.gnu.org/licenses/>.
+ *
+ * The interactive user interfaces in modified source and object code versions
+ * of this program must display Appropriate Legal Notices, as required under
+ * Section 5 of the GNU Affero General Public License version 3.
+ *
+ * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
+ * these Appropriate Legal Notices must retain the display of the "EspoCRM" word.
+ ************************************************************************/
+
+namespace Espo\Tools\CategoryTree;
+
+use Espo\Core\Acl;
+use Espo\Core\Exceptions\Error;
+use Espo\Core\Exceptions\Forbidden;
+use Espo\Core\Exceptions\NotFound;
+use Espo\Core\Templates\Entities\CategoryTree;
+use Espo\ORM\Entity;
+use Espo\ORM\EntityManager;
+use Espo\ORM\Query\Part\Expression as Expr;
+use Espo\ORM\Query\UpdateBuilder;
+use Espo\ORM\Repository\Option\SaveOption;
+use Espo\Tools\CategoryTree\Move\MoveParams;
+
+class MoveService
+{
+ private const ATTR_PARENT_ID = 'parentId';
+ private const ATTR_ORDER = 'order';
+
+ public function __construct(
+ private EntityManager $entityManager,
+ private Acl $acl,
+ ) {}
+
+ /**
+ * @throws NotFound
+ * @throws Forbidden
+ * @throws Error
+ */
+ public function move(CategoryTree $entity, MoveParams $params): void
+ {
+ $hasOrder = $entity->hasAttribute(self::ATTR_ORDER);
+
+ if (!$hasOrder && $params->type !== MoveParams::TYPE_INTO) {
+ throw new Error("Order not supported.");
+ }
+
+ $entityType = $entity->getEntityType();
+
+ $reference = null;
+
+ if ($params->referenceId) {
+ $reference = $this->entityManager->getEntityById($entityType, $params->referenceId);
+
+ if (!$reference) {
+ throw new NotFound("No reference record found.");
+ }
+ }
+
+ if ($params->type === MoveParams::TYPE_INTO) {
+ $this->processInto($reference, $entity, $params);
+
+ return;
+ }
+
+ if (!$reference) {
+ throw new Error("No reference.");
+ }
+
+ $parentId = $reference->get(self::ATTR_PARENT_ID);
+
+ if ($parentId !== $entity->get(self::ATTR_PARENT_ID) && $parentId) {
+ $parent = $this->entityManager->getEntityById($entityType, $parentId);
+
+ if ($parent && !$this->acl->checkEntityEdit($parent)) {
+ throw new Forbidden("No edit access to target category.");
+ }
+
+ if ($parent) {
+ $this->checkReferenceNoLoop($parent, $entity);
+ }
+ }
+
+ if ($params->type === MoveParams::TYPE_AFTER) {
+ $this->processAfter($reference, $entity);
+
+ return;
+ }
+
+ $this->processBefore($reference, $entity);
+ }
+
+ private function incrementAfter(Entity $reference): void
+ {
+ $update = UpdateBuilder::create()
+ ->in($reference->getEntityType())
+ ->where([
+ self::ATTR_PARENT_ID => $reference->get(self::ATTR_PARENT_ID),
+ self::ATTR_ORDER . '>' => $reference->get(self::ATTR_ORDER),
+ ])
+ ->set([
+ self::ATTR_ORDER => Expr::add(Expr::column(self::ATTR_ORDER), 2)
+ ])
+ ->build();
+
+ $this->entityManager->getQueryExecutor()->execute($update);
+ }
+
+ private function decrementBefore(Entity $reference): void
+ {
+ $update = UpdateBuilder::create()
+ ->in($reference->getEntityType())
+ ->where([
+ self::ATTR_PARENT_ID => $reference->get(self::ATTR_PARENT_ID),
+ self::ATTR_ORDER . '<' => $reference->get(self::ATTR_ORDER),
+ ])
+ ->set([
+ self::ATTR_ORDER => Expr::subtract(Expr::column(self::ATTR_ORDER), 2)
+ ])
+ ->build();
+
+ $this->entityManager->getQueryExecutor()->execute($update);
+ }
+
+ private function rearrange(Entity $reference): void
+ {
+ $entities = $this->entityManager
+ ->getRDBRepository($reference->getEntityType())
+ ->where([
+ self::ATTR_PARENT_ID => $reference->get(self::ATTR_PARENT_ID),
+ ])
+ ->order(self::ATTR_ORDER)
+ ->find();
+
+ foreach ($entities as $i => $entity) {
+ $entity->set(self::ATTR_ORDER, $i + 1);
+
+ $this->entityManager->saveEntity($entity, [SaveOption::SKIP_ALL => true]);
+ }
+ }
+
+ private function processAfter(Entity $reference, CategoryTree $entity): void
+ {
+ $this->incrementAfter($reference);
+ $this->rearrange($reference);
+
+ $order = ($reference->get(self::ATTR_ORDER) ?? 0) + 1;
+
+ $entity->set(self::ATTR_ORDER, $order);
+ $entity->set(self::ATTR_PARENT_ID, $reference->get(self::ATTR_PARENT_ID));
+
+ $this->entityManager->saveEntity($entity);
+
+ $this->rearrange($reference);
+ }
+
+ private function processBefore(Entity $reference, CategoryTree $entity): void
+ {
+ $this->decrementBefore($reference);
+
+ $order = ($reference->get(self::ATTR_ORDER) ?? 0) - 1;
+
+ $entity->set(self::ATTR_ORDER, $order);
+ $entity->set(self::ATTR_PARENT_ID, $reference->get(self::ATTR_PARENT_ID));
+
+ $this->entityManager->saveEntity($entity);
+
+ $this->rearrange($reference);
+ }
+
+ /**
+ * @throws Forbidden
+ */
+ private function processInto(?Entity $reference, CategoryTree $entity, MoveParams $params): void
+ {
+ if ($reference && !$this->acl->checkEntityEdit($reference)) {
+ throw new Forbidden("No edit access to target category.");
+ }
+
+ if ($reference) {
+ $this->checkReferenceNoLoop($reference, $entity);
+ }
+
+ $entity->setMultiple([
+ self::ATTR_PARENT_ID => $params->referenceId,
+ self::ATTR_ORDER => null,
+ ]);
+
+ $this->entityManager->saveEntity($entity);
+ }
+
+ /**
+ * @throws Forbidden
+ */
+ private function checkReferenceNoLoop(Entity $reference, CategoryTree $entity): void
+ {
+ $parentId = $reference->get(self::ATTR_PARENT_ID);
+
+ if (!$parentId) {
+ return;
+ }
+
+ if ($parentId === $entity->getId()) {
+ throw new Forbidden("Cannot move. Circle reference.");
+ }
+
+ $parent = $this->entityManager->getEntityById($entity->getEntityType(), $parentId);
+
+ if (!$parent) {
+ return;
+ }
+
+ $this->checkReferenceNoLoop($parent, $entity);
+ }
+}
diff --git a/client/src/views/record/list-tree.js b/client/src/views/record/list-tree.js
index 51f9909f8d..482ed839b4 100644
--- a/client/src/views/record/list-tree.js
+++ b/client/src/views/record/list-tree.js
@@ -77,6 +77,18 @@ class ListTreeRecordView extends ListRecordView {
*/
blockDraggable = false
+ /**
+ * @private
+ * @type {boolean}
+ */
+ moveSupported
+
+ /**
+ * @private
+ * {Draggable}
+ */
+ draggable
+
// noinspection JSCheckFunctionSignatures
data() {
const data = super.data();
@@ -163,12 +175,14 @@ class ListTreeRecordView extends ListRecordView {
}
});
}
+
+ this.moveSupported = !!this.getMetadata().get(`entityDefs.${this.entityType}.fields.order`);
}
afterRender() {
super.afterRender();
- if (this.level === 0 && !this.readOnly) {
+ if (this.level === 0 && !this.readOnly && this.moveSupported) {
this.initDraggableRoot();
}
}
@@ -179,8 +193,7 @@ class ListTreeRecordView extends ListRecordView {
setSelected(id) {
if (id === null) {
this.selectedData.id = null;
- }
- else {
+ } else {
this.selectedData.id = id;
}
@@ -200,6 +213,13 @@ class ListTreeRecordView extends ListRecordView {
});
}
+ /**
+ * @return {import('views/record/list-tree-item').default[]}
+ */
+ getItemViews() {
+ return this.rowList.map(key => this.getView(key));
+ }
+
buildRows(callback) {
this.checkedList = [];
this.rowList = [];
@@ -285,12 +305,10 @@ class ListTreeRecordView extends ListRecordView {
attributes.parentName = this.model.attributes.name;
}
- const scope = this.collection.entityType;
-
const helper = new RecordModal();
helper.showCreate(this, {
- entityType: scope,
+ entityType: this.entityType,
attributes: attributes,
afterSave: model => {
const collection = /** @type {import('collections/tree').default} collection */
@@ -335,9 +353,11 @@ class ListTreeRecordView extends ListRecordView {
* @private
*/
initDraggableRoot() {
- // @todo Test touchscreen.
+ if (this.draggable) {
+ this.draggable.destroy();
+ }
- const draggable = new Draggable(this.element, {
+ const draggable = this.draggable = new Draggable(this.element, {
distance: 8,
draggable: '.list-group-item > .cell > .link',
mirror: {
@@ -460,6 +480,10 @@ class ListTreeRecordView extends ListRecordView {
break;
}
+ if (!itemId && !itemParentId) {
+ continue;
+ }
+
isAfter = itemIsAfter;
overParentId = itemParentId;
overId = itemId;
@@ -486,7 +510,7 @@ class ListTreeRecordView extends ListRecordView {
}
});
- draggable.on('drag:stop', () => {
+ draggable.on('drag:stop', async () => {
if (movedLink) {
movedLink.classList.remove('text-info');
}
@@ -498,7 +522,78 @@ class ListTreeRecordView extends ListRecordView {
rows = undefined;
+ let moveType;
+ let referenceId = overId;
+
+ if (overParentId || overId) {
+ if (overParentId) {
+ moveType = 'into';
+ referenceId = overParentId;
+ } else if (isAfter) {
+ moveType = 'after';
+ } else {
+ moveType = 'before';
+ }
+ }
+
+ if (moveType) {
+ this.blockDraggable = true;
+
+ const movedId = this.movedId;
+ const affectedId = referenceId;
+
+ Espo.Ui.notifyWait();
+
+ Espo.Ajax
+ .postRequest(`${this.entityType}/action/move`, {
+ id: this.movedId,
+ referenceId: referenceId,
+ type: moveType,
+ })
+ .then(async () => {
+ /**
+ *
+ * @param {ListTreeRecordView} view
+ * @param {string} movedId
+ * @return {Promise}
+ */
+ const update = async (view, movedId) => {
+ if (view.collection.has(movedId)) {
+ await view.collection.fetch();
+
+ return;
+ }
+
+ for (const subView of view.getItemViews()) {
+ if (!subView.getChildrenView()) {
+ continue;
+ }
+
+ await update(subView.getChildrenView(), movedId);
+ }
+ };
+
+ const promises = [];
+
+ if (movedId) {
+ promises.push(update(this, movedId));
+ }
+
+ if (affectedId) {
+ promises.push(update(this, affectedId));
+ }
+
+ await Promise.all(promises);
+
+ Espo.Ui.success(this.translate('Done'));
+ })
+ .finally(() => {
+ this.blockDraggable = false;
+ });
+ }
+
this.movedId = null;
+
movedLink = null;
movedFromLi = null;
levelMap = undefined;
@@ -506,11 +601,6 @@ class ListTreeRecordView extends ListRecordView {
overId = null;
isAfter = false;
wasOutOfSelf = false;
-
- // @todo Skip if no change.
-
-
- //this.blockDraggable = true;
});
}
}