EspoCRM – Open Source CRM Application
PHP calendarcontactscrmcrm-platformcrm-systemcustomer-portalcustomer-supportcustomizabledocumentsemail-marketingkanbanleadsopen-sourcephpplatformsales-automationsingle-page-applicationsupport
f/pipeline (#3624)
Yurii Kuznietsov7f6ccfaa8fee
diff --git a/application/Espo/Classes/Acl/Common/Pipeline/PipelineLinkChecker.php b/application/Espo/Classes/Acl/Common/Pipeline/PipelineLinkChecker.phpnew file mode 100644index 0000000000..2d8980ae70--- /dev/null+++ b/application/Espo/Classes/Acl/Common/Pipeline/PipelineLinkChecker.php@@ -0,0 +1,58 @@+<?php+/************************************************************************+ * This file is part of EspoCRM.+ *+ * EspoCRM – Open Source CRM application.+ * Copyright (C) 2014-2026 EspoCRM, Inc.+ * 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\Classes\Acl\Common\Pipeline;++use Espo\Core\Acl\LinkChecker;+use Espo\Entities\Pipeline;+use Espo\Entities\User;+use Espo\ORM\Entity;++/**+ * @implements LinkChecker<Entity, Pipeline>+ */+class PipelineLinkChecker implements LinkChecker+{+ public function check(User $user, Entity $entity, Entity $foreignEntity): bool+ {+ if ($user->isAdmin()) {+ return true;+ }++ if ($foreignEntity->isAvailableForAll()) {+ return true;+ }++ if (!$user->isPortal()) {+ return false;+ }++ return array_intersect($user->getTeamIdList(), $foreignEntity->getTeams()->getIdList()) !== [];+ }+}diff --git a/application/Espo/Classes/Acl/Common/Pipeline/PipelineStageLinkChecker.php b/application/Espo/Classes/Acl/Common/Pipeline/PipelineStageLinkChecker.phpnew file mode 100644index 0000000000..bbe5b5b37c--- /dev/null+++ b/application/Espo/Classes/Acl/Common/Pipeline/PipelineStageLinkChecker.php@@ -0,0 +1,57 @@+<?php+/************************************************************************+ * This file is part of EspoCRM.+ *+ * EspoCRM – Open Source CRM application.+ * Copyright (C) 2014-2026 EspoCRM, Inc.+ * 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\Classes\Acl\Common\Pipeline;++use Espo\Core\Acl\LinkChecker;+use Espo\Core\Name\Field;+use Espo\Entities\PipelineStage;+use Espo\Entities\User;+use Espo\ORM\Entity;++/**+ * @implements LinkChecker<Entity, PipelineStage>+ */+class PipelineStageLinkChecker implements LinkChecker+{+ public function check(User $user, Entity $entity, Entity $foreignEntity): bool+ {+ $pipelineId = $entity->get(Field::PIPELINE . 'Id');++ if (!$pipelineId) {+ return false;+ }++ if ($pipelineId !== $foreignEntity->getPipeline()->getId()) {+ return false;+ }++ return true;+ }+}diff --git a/application/Espo/Classes/Acl/Pipeline/AccessChecker.php b/application/Espo/Classes/Acl/Pipeline/AccessChecker.phpnew file mode 100644index 0000000000..070afcb422--- /dev/null+++ b/application/Espo/Classes/Acl/Pipeline/AccessChecker.php@@ -0,0 +1,108 @@+<?php+/************************************************************************+ * This file is part of EspoCRM.+ *+ * EspoCRM – Open Source CRM application.+ * Copyright (C) 2014-2026 EspoCRM, Inc.+ * 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\Classes\Acl\Pipeline;++use Espo\Core\Acl\AccessEntityCREDChecker;+use Espo\Core\Acl\ScopeData;+use Espo\Core\AclManager;+use Espo\Entities\Pipeline;+use Espo\Entities\User;+use Espo\ORM\Entity;++/**+ * @implements AccessEntityCREDChecker<Pipeline>+ */+class AccessChecker implements AccessEntityCREDChecker+{+ public function __construct(+ private AclManager $aclManager,+ ) {}++ public function check(User $user, ScopeData $data): bool+ {+ return $data->isTrue();+ }++ public function checkCreate(User $user, ScopeData $data): bool+ {+ return $user->isAdmin();+ }++ public function checkRead(User $user, ScopeData $data): bool+ {+ return $data->isTrue();+ }++ public function checkEdit(User $user, ScopeData $data): bool+ {+ return $user->isAdmin();+ }++ public function checkDelete(User $user, ScopeData $data): bool+ {+ return $user->isAdmin();+ }++ public function checkEntityCreate(User $user, Entity $entity, ScopeData $data): bool+ {+ return $user->isAdmin();+ }++ public function checkEntityDelete(User $user, Entity $entity, ScopeData $data): bool+ {+ return $user->isAdmin();+ }++ public function checkEntityEdit(User $user, Entity $entity, ScopeData $data): bool+ {+ return $user->isAdmin();+ }++ public function checkEntityRead(User $user, Entity $entity, ScopeData $data): bool+ {+ if ($user->isAdmin()) {+ return true;+ }++ if (!$data->isFalse()) {+ return false;+ }++ if (!$this->aclManager->checkScope($user, $entity->getTargetEntityType())) {+ return false;+ }++ if ($entity->isAvailableForAll()) {+ return true;+ }++ return array_intersect($user->getTeamIdList(), $entity->getTeams()->getIdList()) !== [];+ }+}diff --git a/application/Espo/Classes/Acl/PipelineStage/AccessChecker.php b/application/Espo/Classes/Acl/PipelineStage/AccessChecker.phpnew file mode 100644index 0000000000..3272eeec33--- /dev/null+++ b/application/Espo/Classes/Acl/PipelineStage/AccessChecker.php@@ -0,0 +1,110 @@+<?php+/************************************************************************+ * This file is part of EspoCRM.+ *+ * EspoCRM – Open Source CRM application.+ * Copyright (C) 2014-2026 EspoCRM, Inc.+ * 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\Classes\Acl\PipelineStage;++use Espo\Core\Acl\AccessEntityCREDChecker;+use Espo\Core\Acl\ScopeData;+use Espo\Core\AclManager;+use Espo\Entities\PipelineStage;+use Espo\Entities\User;+use Espo\ORM\Entity;++/**+ * @implements AccessEntityCREDChecker<PipelineStage>+ */+class AccessChecker implements AccessEntityCREDChecker+{+ public function __construct(+ private AclManager $aclManager,+ ) {}++ public function check(User $user, ScopeData $data): bool+ {+ return $data->isTrue();+ }++ public function checkCreate(User $user, ScopeData $data): bool+ {+ return $user->isAdmin();+ }++ public function checkRead(User $user, ScopeData $data): bool+ {+ return $data->isTrue();+ }++ public function checkEdit(User $user, ScopeData $data): bool+ {+ return $user->isAdmin();+ }++ public function checkDelete(User $user, ScopeData $data): bool+ {+ return $user->isAdmin();+ }++ public function checkEntityCreate(User $user, Entity $entity, ScopeData $data): bool+ {+ return $user->isAdmin();+ }++ public function checkEntityDelete(User $user, Entity $entity, ScopeData $data): bool+ {+ return $user->isAdmin();+ }++ public function checkEntityEdit(User $user, Entity $entity, ScopeData $data): bool+ {+ return $user->isAdmin();+ }++ public function checkEntityRead(User $user, Entity $entity, ScopeData $data): bool+ {+ if ($user->isAdmin()) {+ return true;+ }++ if (!$data->isFalse()) {+ return false;+ }++ $pipeline = $entity->getPipeline();++ if (!$this->aclManager->checkScope($user, $pipeline->getTargetEntityType())) {+ return false;+ }++ if ($pipeline->isAvailableForAll()) {+ return true;+ }++ return array_intersect($user->getTeamIdList(), $pipeline->getTeams()->getIdList()) !== [];+ }+}diff --git a/application/Espo/Classes/AclPortal/Pipeline/AccessChecker.php b/application/Espo/Classes/AclPortal/Pipeline/AccessChecker.phpnew file mode 100644index 0000000000..bb4e0a49b0--- /dev/null+++ b/application/Espo/Classes/AclPortal/Pipeline/AccessChecker.php@@ -0,0 +1,104 @@+<?php+/************************************************************************+ * This file is part of EspoCRM.+ *+ * EspoCRM – Open Source CRM application.+ * Copyright (C) 2014-2026 EspoCRM, Inc.+ * 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\Classes\AclPortal\Pipeline;++use Espo\Core\Acl\AccessEntityCREDChecker;+use Espo\Core\Acl\ScopeData;+use Espo\Core\Portal\AclManager as PortalAclManager;+use Espo\Entities\Pipeline;+use Espo\Entities\User;+use Espo\ORM\Entity;++/**+ * @implements AccessEntityCREDChecker<Pipeline>+ */+class AccessChecker implements AccessEntityCREDChecker+{+ public function __construct(+ private PortalAclManager $aclManager+ ) {}++ public function check(User $user, ScopeData $data): bool+ {+ return $data->isTrue();+ }++ public function checkCreate(User $user, ScopeData $data): bool+ {+ return false;+ }++ public function checkRead(User $user, ScopeData $data): bool+ {+ return $data->isTrue();+ }++ public function checkEdit(User $user, ScopeData $data): bool+ {+ return false;+ }++ public function checkDelete(User $user, ScopeData $data): bool+ {+ return false;+ }++ public function checkEntityCreate(User $user, Entity $entity, ScopeData $data): bool+ {+ return false;+ }++ public function checkEntityDelete(User $user, Entity $entity, ScopeData $data): bool+ {+ return false;+ }++ public function checkEntityEdit(User $user, Entity $entity, ScopeData $data): bool+ {+ return false;+ }++ public function checkEntityRead(User $user, Entity $entity, ScopeData $data): bool+ {+ if (!$data->isFalse()) {+ return false;+ }++ if (!$this->aclManager->checkScope($user, $entity->getTargetEntityType())) {+ return false;+ }++ if ($entity->isAvailableForAll()) {+ return true;+ }++ return false;+ }+}diff --git a/application/Espo/Classes/AclPortal/PipelineStage/AccessChecker.php b/application/Espo/Classes/AclPortal/PipelineStage/AccessChecker.phpnew file mode 100644index 0000000000..f461f476f7--- /dev/null+++ b/application/Espo/Classes/AclPortal/PipelineStage/AccessChecker.php@@ -0,0 +1,106 @@+<?php+/************************************************************************+ * This file is part of EspoCRM.+ *+ * EspoCRM – Open Source CRM application.+ * Copyright (C) 2014-2026 EspoCRM, Inc.+ * 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\Classes\AclPortal\PipelineStage;++use Espo\Core\Acl\AccessEntityCREDChecker;+use Espo\Core\Acl\ScopeData;+use Espo\Core\Portal\AclManager as PortalAclManager;+use Espo\Entities\PipelineStage;+use Espo\Entities\User;+use Espo\ORM\Entity;++/**+ * @implements AccessEntityCREDChecker<PipelineStage>+ */+class AccessChecker implements AccessEntityCREDChecker+{+ public function __construct(+ private PortalAclManager $aclManager+ ) {}++ public function check(User $user, ScopeData $data): bool+ {+ return $data->isTrue();+ }++ public function checkCreate(User $user, ScopeData $data): bool+ {+ return false;+ }++ public function checkRead(User $user, ScopeData $data): bool+ {+ return $data->isTrue();+ }++ public function checkEdit(User $user, ScopeData $data): bool+ {+ return false;+ }++ public function checkDelete(User $user, ScopeData $data): bool+ {+ return false;+ }++ public function checkEntityCreate(User $user, Entity $entity, ScopeData $data): bool+ {+ return false;+ }++ public function checkEntityDelete(User $user, Entity $entity, ScopeData $data): bool+ {+ return false;+ }++ public function checkEntityEdit(User $user, Entity $entity, ScopeData $data): bool+ {+ return false;+ }++ public function checkEntityRead(User $user, Entity $entity, ScopeData $data): bool+ {+ if (!$data->isFalse()) {+ return false;+ }++ $pipeline = $entity->getPipeline();++ if (!$this->aclManager->checkScope($user, $pipeline->getTargetEntityType())) {+ return false;+ }++ if ($pipeline->isAvailableForAll()) {+ return true;+ }++ return false;+ }+}diff --git a/application/Espo/Classes/AppParams/Pipelines.php b/application/Espo/Classes/AppParams/Pipelines.phpnew file mode 100644index 0000000000..881d1d547f--- /dev/null+++ b/application/Espo/Classes/AppParams/Pipelines.php@@ -0,0 +1,56 @@+<?php+/************************************************************************+ * This file is part of EspoCRM.+ *+ * EspoCRM – Open Source CRM application.+ * Copyright (C) 2014-2026 EspoCRM, Inc.+ * 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\Classes\AppParams;++use Espo\Tools\App\AppParam;+use Espo\Tools\Pipeline\Data\PipelineData;+use Espo\Tools\Pipeline\PipelineDataProvider;+use Espo\Tools\Pipeline\PipelineDataUserFilter;++/**+ * @noinspection PhpUnused+ */+class Pipelines implements AppParam+{+ public function __construct(+ private PipelineDataProvider $pipelineDataProvider,+ private PipelineDataUserFilter $userFilter,+ ) {}++ /**+ * @return array<string, PipelineData[]>+ */+ public function get(): array+ {+ $data = $this->pipelineDataProvider->get();++ return $this->userFilter->filter($data);+ }+}diff --git a/application/Espo/Classes/FieldValidators/Common/PipelineStage/Valid.php b/application/Espo/Classes/FieldValidators/Common/PipelineStage/Valid.phpnew file mode 100644index 0000000000..db246b5124--- /dev/null+++ b/application/Espo/Classes/FieldValidators/Common/PipelineStage/Valid.php@@ -0,0 +1,70 @@+<?php+/************************************************************************+ * This file is part of EspoCRM.+ *+ * EspoCRM – Open Source CRM application.+ * Copyright (C) 2014-2026 EspoCRM, Inc.+ * 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\Classes\FieldValidators\Common\PipelineStage;++use Espo\Core\FieldValidation\Validator;+use Espo\Core\FieldValidation\Validator\Data;+use Espo\Core\FieldValidation\Validator\Failure;+use Espo\Core\Name\Field;+use Espo\Entities\PipelineStage;+use Espo\ORM\Entity;+use Espo\ORM\EntityManager;++/**+ * @implements Validator<Entity>+ */+class Valid implements Validator+{+ public function __construct(+ private EntityManager $entityManager,+ ) {}++ public function validate(Entity $entity, string $field, Data $data): ?Failure+ {+ $pipelineId = $entity->get(Field::PIPELINE . 'Id');+ $stageId = $entity->get(Field::PIPELINE_STAGE . 'Id');++ if (!$pipelineId && $stageId) {+ return Failure::create();+ }++ $stage = $this->entityManager->getRDBRepositoryByClass(PipelineStage::class)->getById($stageId);++ if (!$stage) {+ return Failure::create();+ }++ if ($stage->getPipeline()->getId() !== $pipelineId) {+ return Failure::create();+ }++ return null;+ }+}diff --git a/application/Espo/Classes/FieldValidators/Pipeline/EntityType/Valid.php b/application/Espo/Classes/FieldValidators/Pipeline/EntityType/Valid.phpnew file mode 100644index 0000000000..8c5f98325e--- /dev/null+++ b/application/Espo/Classes/FieldValidators/Pipeline/EntityType/Valid.php@@ -0,0 +1,58 @@+<?php+/************************************************************************+ * This file is part of EspoCRM.+ *+ * EspoCRM – Open Source CRM application.+ * Copyright (C) 2014-2026 EspoCRM, Inc.+ * 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\Classes\FieldValidators\Pipeline\EntityType;++use Espo\Core\FieldValidation\Validator;+use Espo\Core\FieldValidation\Validator\Data;+use Espo\Core\FieldValidation\Validator\Failure;+use Espo\Entities\Pipeline;+use Espo\ORM\Entity;+use Espo\Tools\Pipeline\MetadataProvider;++/**+ * @implements Validator<Pipeline>+ */+class Valid implements Validator+{+ public function __construct(+ private MetadataProvider $metadataProvider,+ ) {}++ public function validate(Entity $entity, string $field, Data $data): ?Failure+ {+ $entityType = $entity->getTargetEntityType();++ if (!$this->metadataProvider->isEnabled($entityType)) {+ return Failure::create();+ }++ return null;+ }+}diff --git a/application/Espo/Classes/FieldValidators/Pipeline/Field/Valid.php b/application/Espo/Classes/FieldValidators/Pipeline/Field/Valid.phpnew file mode 100644index 0000000000..726d3c04b8--- /dev/null+++ b/application/Espo/Classes/FieldValidators/Pipeline/Field/Valid.php@@ -0,0 +1,62 @@+<?php+/************************************************************************+ * This file is part of EspoCRM.+ *+ * EspoCRM – Open Source CRM application.+ * Copyright (C) 2014-2026 EspoCRM, Inc.+ * 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\Classes\FieldValidators\Pipeline\Field;++use Espo\Core\FieldValidation\Validator;+use Espo\Core\FieldValidation\Validator\Data;+use Espo\Core\FieldValidation\Validator\Failure;+use Espo\Core\Utils\Metadata;+use Espo\Entities\Pipeline;+use Espo\ORM\Entity;++/**+ * @implements Validator<Pipeline>+ */+class Valid implements Validator+{+ public function __construct(+ private Metadata $metadata,+ ) {}++ public function validate(Entity $entity, string $field, Data $data): ?Failure+ {+ if (!$entity->has(Pipeline::FIELD_FIELD)) {+ return null;+ }++ $field = $entity->getTargetField();++ if ($this->metadata->get("scopes.$field.statusField") !== $field) {+ return Failure::create();+ }++ return null;+ }+}diff --git a/application/Espo/Classes/FieldValidators/PipelineStatus/MappedStatus/Valid.php b/application/Espo/Classes/FieldValidators/PipelineStatus/MappedStatus/Valid.phpnew file mode 100644index 0000000000..9219f79db0--- /dev/null+++ b/application/Espo/Classes/FieldValidators/PipelineStatus/MappedStatus/Valid.php@@ -0,0 +1,80 @@+<?php+/************************************************************************+ * This file is part of EspoCRM.+ *+ * EspoCRM – Open Source CRM application.+ * Copyright (C) 2014-2026 EspoCRM, Inc.+ * 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\Classes\FieldValidators\PipelineStatus\MappedStatus;++use Espo\Core\Utils\Metadata;+use Espo\Entities\PipelineStage;+use Espo\Core\FieldValidation\Validator;+use Espo\Core\FieldValidation\Validator\Data;+use Espo\Core\FieldValidation\Validator\Failure;+use Espo\ORM\Defs;+use Espo\ORM\Entity;+use Espo\Tools\OpenApi\Util\EnumOptionsProvider;++/**+ * @implements Validator<PipelineStage>+ */+class Valid implements Validator+{+ public function __construct(+ private Metadata $metadata,+ private EnumOptionsProvider $enumOptionsProvider,+ private Defs $defs,+ ) {}++ public function validate(Entity $entity, string $field, Data $data): ?Failure+ {+ $status = $entity->getMappedStatus();++ $entityType = $entity->getPipeline()->getTargetEntityType();++ $field = $this->metadata->get("scopes.$entityType.statusField");++ if (!$field) {+ return null;+ }++ $fieldDefs = $this->defs+ ->getEntity($entityType)+ ->getField($field);++ $options = $this->enumOptionsProvider->get($fieldDefs);++ if (!$options) {+ return Failure::create();+ }++ if (!in_array($status, $options)) {+ return Failure::create();+ }++ return null;+ }+}diff --git a/application/Espo/Classes/Record/Hooks/Pipeline/AfterDelete.php b/application/Espo/Classes/Record/Hooks/Pipeline/AfterDelete.phpnew file mode 100644index 0000000000..3d24932b4e--- /dev/null+++ b/application/Espo/Classes/Record/Hooks/Pipeline/AfterDelete.php@@ -0,0 +1,51 @@+<?php+/************************************************************************+ * This file is part of EspoCRM.+ *+ * EspoCRM – Open Source CRM application.+ * Copyright (C) 2014-2026 EspoCRM, Inc.+ * 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\Classes\Record\Hooks\Pipeline;++use Espo\Core\Record\DeleteParams;+use Espo\Core\Record\Hook\DeleteHook;+use Espo\Entities\Pipeline;+use Espo\ORM\Entity;+use Espo\Tools\Pipeline\CacheClearer;++/**+ * @implements DeleteHook<Pipeline>+ */+class AfterDelete implements DeleteHook+{+ public function __construct(+ private CacheClearer $cacheClearer,+ ) {}++ public function process(Entity $entity, DeleteParams $params): void+ {+ $this->cacheClearer->clear();+ }+}diff --git a/application/Espo/Classes/Record/Hooks/Pipeline/AfterSave.php b/application/Espo/Classes/Record/Hooks/Pipeline/AfterSave.phpnew file mode 100644index 0000000000..5a6787caec--- /dev/null+++ b/application/Espo/Classes/Record/Hooks/Pipeline/AfterSave.php@@ -0,0 +1,50 @@+<?php+/************************************************************************+ * This file is part of EspoCRM.+ *+ * EspoCRM – Open Source CRM application.+ * Copyright (C) 2014-2026 EspoCRM, Inc.+ * 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\Classes\Record\Hooks\Pipeline;++use Espo\Core\Record\Hook\SaveHook;+use Espo\Entities\Pipeline;+use Espo\ORM\Entity;+use Espo\Tools\Pipeline\CacheClearer;++/**+ * @implements SaveHook<Pipeline>+ */+class AfterSave implements SaveHook+{+ public function __construct(+ private CacheClearer $cacheClearer,+ ) {}++ public function process(Entity $entity): void+ {+ $this->cacheClearer->clear();+ }+}diff --git a/application/Espo/Classes/Record/Hooks/Pipeline/BeforeDelete.php b/application/Espo/Classes/Record/Hooks/Pipeline/BeforeDelete.phpnew file mode 100644index 0000000000..bbbee819d8--- /dev/null+++ b/application/Espo/Classes/Record/Hooks/Pipeline/BeforeDelete.php@@ -0,0 +1,70 @@+<?php+/************************************************************************+ * This file is part of EspoCRM.+ *+ * EspoCRM – Open Source CRM application.+ * Copyright (C) 2014-2026 EspoCRM, Inc.+ * 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\Classes\Record\Hooks\Pipeline;++use Espo\Core\Exceptions\Conflict;+use Espo\Core\Exceptions\Error\Body;+use Espo\Core\Name\Field;+use Espo\Core\Record\DeleteParams;+use Espo\Core\Record\Hook\DeleteHook;+use Espo\Entities\Pipeline;+use Espo\ORM\Entity;+use Espo\ORM\EntityManager;++/**+ * @implements DeleteHook<Pipeline>+ */+class BeforeDelete implements DeleteHook+{+ public function __construct(+ private EntityManager $entityManager,+ ) {}++ public function process(Entity $entity, DeleteParams $params): void+ {+ $entityType = $entity->getTargetEntityType();++ if (!$this->entityManager->hasRepository($entityType)) {+ return;+ }++ $one = $this->entityManager+ ->getRDBRepository($entityType)+ ->where([Field::PIPELINE . 'Id' => $entity->getId()])+ ->findOne();++ if ($one) {+ throw Conflict::createWithBody(+ 'cannotRemoveUsed',+ Body::create()->withMessageTranslation('cannotRemoveUsed')+ );+ }+ }+}diff --git a/application/Espo/Classes/Record/Hooks/PipelineStage/AfterDelete.php b/application/Espo/Classes/Record/Hooks/PipelineStage/AfterDelete.phpnew file mode 100644index 0000000000..a8c26f8a8a--- /dev/null+++ b/application/Espo/Classes/Record/Hooks/PipelineStage/AfterDelete.php@@ -0,0 +1,50 @@+<?php+/************************************************************************+ * This file is part of EspoCRM.+ *+ * EspoCRM – Open Source CRM application.+ * Copyright (C) 2014-2026 EspoCRM, Inc.+ * 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\Classes\Record\Hooks\PipelineStage;++use Espo\Core\Record\DeleteParams;+use Espo\Core\Record\Hook\DeleteHook;+use Espo\ORM\Entity;+use Espo\Tools\Pipeline\CacheClearer;++/**+ * @noinspection PhpUnused+ */+class AfterDelete implements DeleteHook+{+ public function __construct(+ private CacheClearer $cacheClearer,+ ) {}++ public function process(Entity $entity, DeleteParams $params): void+ {+ $this->cacheClearer->clear();+ }+}diff --git a/application/Espo/Classes/Record/Hooks/PipelineStage/AfterSave.php b/application/Espo/Classes/Record/Hooks/PipelineStage/AfterSave.phpnew file mode 100644index 0000000000..285decd9af--- /dev/null+++ b/application/Espo/Classes/Record/Hooks/PipelineStage/AfterSave.php@@ -0,0 +1,46 @@+<?php+/************************************************************************+ * This file is part of EspoCRM.+ *+ * EspoCRM – Open Source CRM application.+ * Copyright (C) 2014-2026 EspoCRM, Inc.+ * 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\Classes\Record\Hooks\PipelineStage;++use Espo\Core\Record\Hook\SaveHook;+use Espo\ORM\Entity;+use Espo\Tools\Pipeline\CacheClearer;++class AfterSave implements SaveHook+{+ public function __construct(+ private CacheClearer $cacheClearer,+ ) {}++ public function process(Entity $entity): void+ {+ $this->cacheClearer->clear();+ }+}diff --git a/application/Espo/Classes/Select/Pipeline/AccessControlFilters/Mandatory.php b/application/Espo/Classes/Select/Pipeline/AccessControlFilters/Mandatory.phpnew file mode 100644index 0000000000..1a598eaacf--- /dev/null+++ b/application/Espo/Classes/Select/Pipeline/AccessControlFilters/Mandatory.php@@ -0,0 +1,72 @@+<?php+/************************************************************************+ * This file is part of EspoCRM.+ *+ * EspoCRM – Open Source CRM application.+ * Copyright (C) 2014-2026 EspoCRM, Inc.+ * 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\Classes\Select\Pipeline\AccessControlFilters;++use Espo\Core\Select\AccessControl\Filter;+use Espo\Entities\Pipeline;+use Espo\Entities\User;+use Espo\ORM\Name\Attribute;+use Espo\ORM\Query\SelectBuilder;+use Espo\Tools\Pipeline\PipelineDataProvider;+use Espo\Tools\Pipeline\PipelineDataUserFilter;++class Mandatory implements Filter+{+ public function __construct(+ private User $user,+ private PipelineDataProvider $pipelineDataProvider,+ private PipelineDataUserFilter $filter,+ ) {}++ public function apply(SelectBuilder $queryBuilder): void+ {+ if ($this->user->isAdmin()) {+ return;+ }++ $data = $this->pipelineDataProvider->get();+ $data = $this->filter->filter($data);++ $entityTypes = array_keys($data);++ $ids = [];++ foreach ($data as $items) {+ foreach ($items as $item) {+ $ids[] = $item->id;+ }+ }++ $queryBuilder->where([+ Pipeline::FIELD_ENTITY_TYPE => $entityTypes,+ Attribute::ID => $ids,+ ]);+ }+}diff --git a/application/Espo/Classes/Select/Pipeline/PrimaryFilters/Active.php b/application/Espo/Classes/Select/Pipeline/PrimaryFilters/Active.phpnew file mode 100644index 0000000000..d13b4815c7--- /dev/null+++ b/application/Espo/Classes/Select/Pipeline/PrimaryFilters/Active.php@@ -0,0 +1,44 @@+<?php+/************************************************************************+ * This file is part of EspoCRM.+ *+ * EspoCRM – Open Source CRM application.+ * Copyright (C) 2014-2026 EspoCRM, Inc.+ * 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\Classes\Select\Pipeline\PrimaryFilters;++use Espo\Core\Select\Primary\Filter;+use Espo\Entities\Pipeline;+use Espo\ORM\Query\SelectBuilder;++class Active implements Filter+{+ public function apply(SelectBuilder $queryBuilder): void+ {+ $queryBuilder->where([+ Pipeline::FIELD_STATUS => Pipeline::STATUS_ACTIVE,+ ]);+ }+}diff --git a/application/Espo/Classes/Select/PipelineStage/AccessControlFilters/Mandatory.php b/application/Espo/Classes/Select/PipelineStage/AccessControlFilters/Mandatory.phpnew file mode 100644index 0000000000..0eabdb19dd--- /dev/null+++ b/application/Espo/Classes/Select/PipelineStage/AccessControlFilters/Mandatory.php@@ -0,0 +1,77 @@+<?php+/************************************************************************+ * This file is part of EspoCRM.+ *+ * EspoCRM – Open Source CRM application.+ * Copyright (C) 2014-2026 EspoCRM, Inc.+ * 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\Classes\Select\PipelineStage\AccessControlFilters;++use Espo\Core\Select\AccessControl\Filter;+use Espo\Entities\Pipeline;+use Espo\Entities\PipelineStage;+use Espo\Entities\User;+use Espo\ORM\Name\Attribute;+use Espo\ORM\Query\SelectBuilder;+use Espo\Tools\Pipeline\PipelineDataProvider;+use Espo\Tools\Pipeline\PipelineDataUserFilter;++class Mandatory implements Filter+{+ public function __construct(+ private User $user,+ private PipelineDataProvider $pipelineDataProvider,+ private PipelineDataUserFilter $filter,+ ) {}++ public function apply(SelectBuilder $queryBuilder): void+ {+ if ($this->user->isAdmin()) {+ return;+ }++ $data = $this->pipelineDataProvider->get();+ $data = $this->filter->filter($data);++ $entityTypes = array_keys($data);++ $ids = [];++ foreach ($data as $items) {+ foreach ($items as $item) {+ $ids[] = $item->id;+ }+ }++ $alias = 'pipelineAccess';++ $queryBuilder+ ->join(PipelineStage::FIELD_PIPELINE, $alias)+ ->where([+ $alias . '.' . Pipeline::FIELD_ENTITY_TYPE => $entityTypes,+ $alias . '.' . Attribute::ID => $ids,+ ]);+ }+}diff --git a/application/Espo/Classes/Select/PipelineStage/ListOrderOrderer.php b/application/Espo/Classes/Select/PipelineStage/ListOrderOrderer.phpnew file mode 100644index 0000000000..51a9ea36ce--- /dev/null+++ b/application/Espo/Classes/Select/PipelineStage/ListOrderOrderer.php@@ -0,0 +1,49 @@+<?php+/************************************************************************+ * This file is part of EspoCRM.+ *+ * EspoCRM – Open Source CRM application.+ * Copyright (C) 2014-2026 EspoCRM, Inc.+ * 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\Classes\Select\PipelineStage;++use Espo\Core\Select\Order\Item;+use Espo\Core\Select\Order\Orderer;+use Espo\Entities\PipelineStage;+use Espo\ORM\Query\SelectBuilder;++/**+ * @noinspection PhpUnused+ */+class ListOrderOrderer implements Orderer+{+ public function apply(SelectBuilder $queryBuilder, Item $item): void+ {+ $queryBuilder+ ->leftJoin(PipelineStage::FIELD_PIPELINE)+ ->order(PipelineStage::FIELD_PIPELINE . '.' . PipelineStage::FIELD_ORDER, $item->getOrder())+ ->order(PipelineStage::FIELD_ORDER, $item->getOrder());+ }+}diff --git a/application/Espo/Controllers/Pipeline.php b/application/Espo/Controllers/Pipeline.phpnew file mode 100644index 0000000000..c49241d069--- /dev/null+++ b/application/Espo/Controllers/Pipeline.php@@ -0,0 +1,38 @@+<?php+/************************************************************************+ * This file is part of EspoCRM.+ *+ * EspoCRM – Open Source CRM application.+ * Copyright (C) 2014-2026 EspoCRM, Inc.+ * 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\Controllers;++use Espo\Core\Controllers\Record;++/**+ * @noinspection PhpUnused+ */+class Pipeline extends Record+{}diff --git a/application/Espo/Controllers/PipelineStage.php b/application/Espo/Controllers/PipelineStage.phpnew file mode 100644index 0000000000..ab0dbf0f75--- /dev/null+++ b/application/Espo/Controllers/PipelineStage.php@@ -0,0 +1,38 @@+<?php+/************************************************************************+ * This file is part of EspoCRM.+ *+ * EspoCRM – Open Source CRM application.+ * Copyright (C) 2014-2026 EspoCRM, Inc.+ * 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\Controllers;++use Espo\Core\Controllers\RecordBase;++/**+ * @noinspection PhpUnused+ */+class PipelineStage extends RecordBase+{}diff --git a/application/Espo/Core/Name/Field.php b/application/Espo/Core/Name/Field.phpindex c4e8f9d559..6c1ba3c030 100644--- a/application/Espo/Core/Name/Field.php+++ b/application/Espo/Core/Name/Field.php@@ -50,4 +50,14 @@ class Fieldpublic const PHONE_NUMBER = 'phoneNumber';public const VERSION_NUMBER = 'versionNumber';public const string IS_LOCKED = 'isLocked';++ /**+ * @since 9.4.0+ */+ public const string PIPELINE = 'pipeline';++ /**+ * @since 9.4.0+ */+ public const string PIPELINE_STAGE = 'pipelineStage';}diff --git a/application/Espo/Core/Utils/Metadata/AdditionalBuilder/Pipelines.php b/application/Espo/Core/Utils/Metadata/AdditionalBuilder/Pipelines.phpnew file mode 100644index 0000000000..dfc9fdf73a--- /dev/null+++ b/application/Espo/Core/Utils/Metadata/AdditionalBuilder/Pipelines.php@@ -0,0 +1,83 @@+<?php+/************************************************************************+ * This file is part of EspoCRM.+ *+ * EspoCRM – Open Source CRM application.+ * Copyright (C) 2014-2026 EspoCRM, Inc.+ * 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\Core\Utils\Metadata\AdditionalBuilder;++use Espo\Core\Utils\Metadata\AdditionalBuilder;+use stdClass;++/**+ * @noinspection PhpUnused+ */+class Pipelines implements AdditionalBuilder+{+ public function build(stdClass $data): void+ {+ $scopes = $data->scopes ?? null;++ if (!$scopes instanceof stdClass) {+ return;+ }++ foreach (get_object_vars($scopes) as $scope => $itemDefs) {+ if (+ !($itemDefs->entity ?? false) ||+ !($itemDefs->pipelines ?? false)+ ) {+ continue;+ }++ $statusField = $itemDefs->statusField ?? null;++ if (!$statusField) {+ continue;+ }++ $entityDefs = $data->entityDefs->$scope ?? null;++ if (!$entityDefs instanceof stdClass) {+ return;+ }++ $fieldsDefs = $entityDefs->fields ?? null;++ if (!$fieldsDefs instanceof stdClass) {+ return;+ }++ $statusFieldDefs = $fieldsDefs->$statusField ?? null;++ if (!$statusFieldDefs instanceof stdClass) {+ return;+ }++ $statusFieldDefs->readOnly = true;+ }+ }+}diff --git a/application/Espo/Entities/Pipeline.php b/application/Espo/Entities/Pipeline.phpnew file mode 100644index 0000000000..d307664be7--- /dev/null+++ b/application/Espo/Entities/Pipeline.php@@ -0,0 +1,101 @@+<?php+/************************************************************************+ * This file is part of EspoCRM.+ *+ * EspoCRM – Open Source CRM application.+ * Copyright (C) 2014-2026 EspoCRM, Inc.+ * 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\Entities;++use Espo\Core\Field\LinkMultiple;+use Espo\Core\Name\Field;+use Espo\Core\ORM\Entity;+use Espo\ORM\EntityCollection;++class Pipeline extends Entity+{+ public const string ENTITY_TYPE = 'Pipeline';++ public const string FIELD_STATUS = 'status';+ public const string FIELD_ENTITY_TYPE = 'entityType';+ public const string FIELD_FIELD = 'field';+ public const string FIELD_COLOR = 'color';+ public const string FIELD_IS_AVAILABLE_FOR_ALL = 'isAvailableForAll';+ public const string FIELD_ORDER = 'order';++ public const string LINK_STAGES = 'stages';++ public const string STATUS_ACTIVE = 'Active';++ public function getName(): string+ {+ return $this->get(Field::NAME);+ }++ public function getTargetEntityType(): string+ {+ return $this->get(self::FIELD_ENTITY_TYPE);+ }++ public function getTargetField(): string+ {+ return $this->get(self::FIELD_FIELD);+ }++ public function getColor(): ?int+ {+ return $this->get(self::FIELD_COLOR);+ }++ public function isAvailableForAll(): bool+ {+ return $this->get(self::FIELD_IS_AVAILABLE_FOR_ALL);+ }++ public function setTeams(LinkMultiple $teams): self+ {+ return $this->setValueObject(Field::TEAMS, $teams);+ }++ public function getTeams(): LinkMultiple+ {+ /** @var LinkMultiple */+ return $this->getValueObject(Field::TEAMS);+ }++ public function getOrder(): int+ {+ return (int) $this->get(self::FIELD_ORDER);+ }++ /**+ * @return EntityCollection<PipelineStage>+ */+ public function getStages(): EntityCollection+ {+ /** @var EntityCollection<PipelineStage> */+ return $this->relations->getMany(self::LINK_STAGES);+ }+}diff --git a/application/Espo/Entities/PipelineStage.php b/application/Espo/Entities/PipelineStage.phpnew file mode 100644index 0000000000..133f112bfa--- /dev/null+++ b/application/Espo/Entities/PipelineStage.php@@ -0,0 +1,97 @@+<?php+/************************************************************************+ * This file is part of EspoCRM.+ *+ * EspoCRM – Open Source CRM application.+ * Copyright (C) 2014-2026 EspoCRM, Inc.+ * 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\Entities;++use Espo\Core\ORM\Entity;+use UnexpectedValueException;++class PipelineStage extends Entity+{+ public const string ENTITY_TYPE = 'PipelineStage';++ public const string FIELD_MAPPED_STATUS = 'mappedStatus';+ public const string FIELD_ORDER = 'order';+ public const string FIELD_PIPELINE = 'pipeline';+ public const string FIELD_NAME = 'name';++ public const string ATTR_PIPELINE_ID = 'pipelineId';++ public function getName(): string+ {+ return $this->get(self::FIELD_NAME);+ }++ public function setName(string $name): self+ {+ $this->set(self::FIELD_NAME, $name);++ return $this;+ }++ public function setMappedStatus(string $status): self+ {+ $this->set(self::FIELD_MAPPED_STATUS, $status);++ return $this;+ }++ public function getMappedStatus(): string+ {+ return $this->get(self::FIELD_MAPPED_STATUS);+ }++ public function getOrder(): int+ {+ return (int) $this->get(self::FIELD_ORDER);+ }++ public function setOrder(int $order): self+ {+ $this->set(self::FIELD_ORDER, $order);++ return $this;+ }++ public function setPipeline(Pipeline $pipeline): self+ {+ return $this->setRelatedLinkOrEntity(self::FIELD_PIPELINE, $pipeline);+ }++ public function getPipeline(): Pipeline+ {+ $pipeline = $this->relations->getOne(self::FIELD_PIPELINE);++ if (!$pipeline instanceof Pipeline) {+ throw new UnexpectedValueException("No pipeline.");+ }++ return $pipeline;+ }+}diff --git a/application/Espo/Hooks/Common/PipelineStageStatus.php b/application/Espo/Hooks/Common/PipelineStageStatus.phpnew file mode 100644index 0000000000..56aa342331--- /dev/null+++ b/application/Espo/Hooks/Common/PipelineStageStatus.php@@ -0,0 +1,83 @@+<?php+/************************************************************************+ * This file is part of EspoCRM.+ *+ * EspoCRM – Open Source CRM application.+ * Copyright (C) 2014-2026 EspoCRM, Inc.+ * 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\Hooks\Common;++use Espo\Entities\PipelineStage;+use Espo\Core\Hook\Hook\BeforeSave;+use Espo\Core\Name\Field;+use Espo\ORM\Entity;+use Espo\ORM\EntityManager;+use Espo\ORM\Repository\Option\SaveOptions;+use Espo\Tools\Pipeline\MetadataProvider;++/**+ * @noinspection PhpUnused+ */+class PipelineStageStatus implements BeforeSave+{+ public static int $order = 1;++ public function __construct(+ private MetadataProvider $metadataProvider,+ private EntityManager $entityManager,+ ) {}++ public function beforeSave(Entity $entity, SaveOptions $options): void+ {+ if (!$this->metadataProvider->isEnabled($entity->getEntityType())) {+ return;+ }++ $statusField = $this->metadataProvider->getStatusField($entity->getEntityType());++ if (!$statusField) {+ return;+ }++ if (+ !$entity->isAttributeChanged(Field::PIPELINE . 'Id') &&+ !$entity->isAttributeChanged(Field::PIPELINE_STAGE . 'Id')+ ) {+ return;+ }++ $status = null;++ $stageId = $entity->get(Field::PIPELINE_STAGE . 'Id');++ if ($stageId) {+ $stage = $this->entityManager->getRDBRepositoryByClass(PipelineStage::class)->getById($stageId);++ $status = $stage?->getMappedStatus() ?? null;+ }++ $entity->set($statusField, $status);+ }+}diff --git a/application/Espo/Hooks/Common/PipelineStageValidation.php b/application/Espo/Hooks/Common/PipelineStageValidation.phpnew file mode 100644index 0000000000..a3071d1f13--- /dev/null+++ b/application/Espo/Hooks/Common/PipelineStageValidation.php@@ -0,0 +1,81 @@+<?php+/************************************************************************+ * This file is part of EspoCRM.+ *+ * EspoCRM – Open Source CRM application.+ * Copyright (C) 2014-2026 EspoCRM, Inc.+ * 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\Hooks\Common;++use Espo\Core\Hook\Hook\BeforeSave;+use Espo\Core\Name\Field;+use Espo\Entities\PipelineStage;+use Espo\ORM\Entity;+use Espo\ORM\EntityManager;+use Espo\ORM\Exceptions\ValidationException;+use Espo\ORM\Repository\Option\SaveOptions;+use Espo\Tools\Pipeline\MetadataProvider;++/**+ * @noinspection PhpUnused+ */+class PipelineStageValidation implements BeforeSave+{+ public function __construct(+ private MetadataProvider $metadataProvider,+ private EntityManager $entityManager,+ ) {}++ public function beforeSave(Entity $entity, SaveOptions $options): void+ {+ if (!$this->metadataProvider->isEnabled($entity->getEntityType())) {+ return;+ }++ if (+ !$entity->isAttributeChanged(Field::PIPELINE . 'Id') &&+ !$entity->isAttributeChanged(Field::PIPELINE_STAGE . 'Id')+ ) {+ return;+ }++ $pipelineId = $entity->get(Field::PIPELINE . 'Id');+ $stageId = $entity->get(Field::PIPELINE_STAGE . 'Id');++ if (!$stageId) {+ return;+ }++ $stage = $this->entityManager->getRDBRepositoryByClass(PipelineStage::class)->getById($stageId);++ if (!$stage) {+ throw new ValidationException("Pipeline stage '$stageId' does not exist.");+ }++ if ($stage->getPipeline()->getId() !== $pipelineId) {+ throw new ValidationException("Pipeline stage does not belong to the set pipelined.");+ }+ }+}diff --git a/application/Espo/Hooks/Pipeline/CreateStages.php b/application/Espo/Hooks/Pipeline/CreateStages.phpnew file mode 100644index 0000000000..35f9755f07--- /dev/null+++ b/application/Espo/Hooks/Pipeline/CreateStages.php@@ -0,0 +1,120 @@+<?php+/************************************************************************+ * This file is part of EspoCRM.+ *+ * EspoCRM – Open Source CRM application.+ * Copyright (C) 2014-2026 EspoCRM, Inc.+ * 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\Hooks\Pipeline;++use Espo\Core\Hook\Hook\AfterSave;+use Espo\Core\ORM\Repository\Option\SaveOption;+use Espo\Core\Utils\Language;+use Espo\Entities\Pipeline;+use Espo\Entities\PipelineStage;+use Espo\ORM\Defs;+use Espo\ORM\Entity;+use Espo\ORM\EntityManager;+use Espo\ORM\Repository\Option\SaveOptions;+use Espo\Tools\OpenApi\Util\EnumOptionsProvider;++/**+ * @implements AfterSave<Pipeline>+ */+class CreateStages implements AfterSave+{+ public function __construct(+ private EntityManager $entityManager,+ private Language $defaultLanguage,+ private Defs $defs,+ private EnumOptionsProvider $enumOptionsProvider,+ ) {}++ public function afterSave(Entity $entity, SaveOptions $options): void+ {+ $targetEntityType = $entity->getTargetEntityType();+ $field = $entity->getTargetField();++ if (+ !$entity->isNew() ||+ !$options->get(SaveOption::API) && !$options->get('createStages')+ ) {+ return;+ }++ if ($options->get(SaveOption::DUPLICATE_SOURCE_ID)) {+ $this->processDuplicate($entity, $options->get(SaveOption::DUPLICATE_SOURCE_ID));++ return;+ }++ $fieldDefs = $this->defs+ ->getEntity($targetEntityType)+ ->getField($field);++ $options = $this->enumOptionsProvider->get($fieldDefs) ?? [];++ foreach ($options as $i => $option) {+ $column = $this->entityManager->getRDBRepositoryByClass(PipelineStage::class)->getNew();++ $name = $this->defaultLanguage->translateOption($option, $field, $targetEntityType);++ $column+ ->setName($name)+ ->setMappedStatus($option)+ ->setPipeline($entity)+ ->setOrder($i);++ $this->entityManager->saveEntity($column);+ }+ }++ private function processDuplicate(Pipeline $entity, string $sourceId): void+ {+ $source = $this->entityManager->getRDBRepositoryByClass(Pipeline::class)->getById($sourceId);++ if (!$source) {+ return;+ }++ /** @var iterable<PipelineStage> $sourceStages */+ $sourceStages = $this->entityManager+ ->getRelation($source, Pipeline::LINK_STAGES)+ ->order(PipelineStage::FIELD_ORDER)+ ->find();++ foreach ($sourceStages as $i => $sourceStage) {+ $stage = $this->entityManager->getRDBRepositoryByClass(PipelineStage::class)->getNew();++ $stage+ ->setName($sourceStage->getName())+ ->setMappedStatus($sourceStage->getMappedStatus())+ ->setOrder($i)+ ->setPipeline($entity);++ $this->entityManager->saveEntity($stage);+ }+ }+}diff --git a/application/Espo/Hooks/Pipeline/Order.php b/application/Espo/Hooks/Pipeline/Order.phpnew file mode 100644index 0000000000..57ad7a1451--- /dev/null+++ b/application/Espo/Hooks/Pipeline/Order.php@@ -0,0 +1,90 @@+<?php+/************************************************************************+ * This file is part of EspoCRM.+ *+ * EspoCRM – Open Source CRM application.+ * Copyright (C) 2014-2026 EspoCRM, Inc.+ * 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\Hooks\Pipeline;++use Espo\Core\Hook\Hook\AfterRemove;+use Espo\Core\Hook\Hook\BeforeSave;+use Espo\Entities\Pipeline;+use Espo\Tools\Pipeline\MoveService;+use Espo\ORM\Entity;+use Espo\ORM\EntityManager;+use Espo\ORM\Name\Attribute;+use Espo\ORM\Query\Part\Expression as Expr;+use Espo\ORM\Query\Part\Order as OrderPart;+use Espo\ORM\Query\SelectBuilder;+use Espo\ORM\Repository\Option\RemoveOptions;+use Espo\ORM\Repository\Option\SaveOptions;++/**+ * @implements BeforeSave<Pipeline>+ * @implements AfterRemove<Pipeline>+ */+class Order implements BeforeSave, AfterRemove+{+ public function __construct(+ private EntityManager $entityManager,+ private MoveService $moveService,+ ) {}++ public function beforeSave(Entity $entity, SaveOptions $options): void+ {+ if (!$entity->isNew()) {+ return;+ }++ $entityType = $entity->getTargetEntityType();++ $query = SelectBuilder::create()+ ->from(Pipeline::ENTITY_TYPE)+ ->select(Expr::max(Expr::column(Pipeline::FIELD_ORDER)), 'max')+ ->select(Attribute::ID)+ ->group(Attribute::ID)+ ->limit(0, 1)+ ->order(Expr::max(Expr::column(Pipeline::FIELD_ORDER)), OrderPart::DESC)+ ->where([+ Pipeline::FIELD_ENTITY_TYPE => $entityType,+ ])+ ->build();++ $sth = $this->entityManager->getQueryExecutor()->execute($query);++ $row = $sth->fetch();++ $order = $row ? $row['max'] : 0;+ $order ++;++ $entity->set(Pipeline::FIELD_ORDER, $order);+ }++ public function afterRemove(Entity $entity, RemoveOptions $options): void+ {+ $this->moveService->reOrder($entity::class);+ }+}diff --git a/application/Espo/Hooks/Pipeline/SetFields.php b/application/Espo/Hooks/Pipeline/SetFields.phpnew file mode 100644index 0000000000..f305d00795--- /dev/null+++ b/application/Espo/Hooks/Pipeline/SetFields.php@@ -0,0 +1,62 @@+<?php+/************************************************************************+ * This file is part of EspoCRM.+ *+ * EspoCRM – Open Source CRM application.+ * Copyright (C) 2014-2026 EspoCRM, Inc.+ * 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\Hooks\Pipeline;++use Espo\Core\Field\LinkMultiple;+use Espo\Core\Hook\Hook\BeforeSave;+use Espo\Core\Utils\Metadata;+use Espo\Entities\Pipeline;+use Espo\ORM\Entity;+use Espo\ORM\Repository\Option\SaveOptions;++/**+ * @implements BeforeSave<Pipeline>+ */+class SetFields implements BeforeSave+{+ public function __construct(+ private Metadata $metadata,+ ) {}++ public function beforeSave(Entity $entity, SaveOptions $options): void+ {+ if ($entity->isAvailableForAll()) {+ $entity->setTeams(LinkMultiple::create());+ }++ if ($entity->isNew()) {+ $entityType = $entity->getTargetEntityType();++ $field = $this->metadata->get("scopes.$entityType.statusField");++ $entity->set(Pipeline::FIELD_FIELD, $field);+ }+ }+}diff --git a/application/Espo/Hooks/PipelineStage/Order.php b/application/Espo/Hooks/PipelineStage/Order.phpnew file mode 100644index 0000000000..5083012d46--- /dev/null+++ b/application/Espo/Hooks/PipelineStage/Order.php@@ -0,0 +1,128 @@+<?php+/************************************************************************+ * This file is part of EspoCRM.+ *+ * EspoCRM – Open Source CRM application.+ * Copyright (C) 2014-2026 EspoCRM, Inc.+ * 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\Hooks\PipelineStage;++use Espo\Core\Hook\Hook\AfterRemove;+use Espo\Core\Hook\Hook\BeforeSave;+use Espo\Core\ORM\Repository\Option\SaveOption;+use Espo\Entities\Pipeline;+use Espo\Entities\PipelineStage;+use Espo\Tools\Pipeline\MoveService;+use Espo\ORM\Collection;+use Espo\ORM\Defs;+use Espo\ORM\Entity;+use Espo\ORM\EntityManager;+use Espo\ORM\Repository\Option\RemoveOptions;+use Espo\ORM\Repository\Option\SaveOptions;+use Espo\Tools\OpenApi\Util\EnumOptionsProvider;++/**+ * @implements BeforeSave<PipelineStage>+ * @implements AfterRemove<PipelineStage>+ */+class Order implements BeforeSave, AfterRemove+{+ public function __construct(+ private EntityManager $entityManager,+ private MoveService $moveService,+ private Defs $defs,+ private EnumOptionsProvider $enumOptionsProvider,+ ) {}++ public function beforeSave(Entity $entity, SaveOptions $options): void+ {+ if (!$entity->isNew()) {+ return;+ }++ $stages = $this->getStages($entity);++ $i = 0;+ $newList = [];++ foreach ($this->getStatusList($entity) as $status) {+ foreach ($stages as $stage) {+ if ($stage->getMappedStatus() === $status) {+ $newList[] = $stage;++ $stage->setOrder($i);+ $i++;+ }+ }++ if ($entity->getMappedStatus() === $status) {+ $newList[] = $entity;++ $entity->setOrder($i);+ $i++;+ }+ }++ foreach ($newList as $stage) {+ if ($stage->getId() === $entity->getId()) {+ continue;+ }++ $this->entityManager->saveEntity($stage, [SaveOption::SILENT => true]);+ }+ }++ public function afterRemove(Entity $entity, RemoveOptions $options): void+ {+ $this->moveService->reOrder($entity::class, $entity->get(PipelineStage::ATTR_PIPELINE_ID));+ }++ /**+ * @return iterable<PipelineStage>+ */+ private function getStages(PipelineStage $entity): iterable+ {+ /** @var Collection<PipelineStage> */+ return $this->entityManager+ ->getRelation($entity->getPipeline(), Pipeline::LINK_STAGES)+ ->order(PipelineStage::FIELD_ORDER)+ ->find();+ }++ /**+ * @return string[]+ */+ private function getStatusList(PipelineStage $entity): array+ {+ $targetEntityType = $entity->getPipeline()->getTargetEntityType();+ $field = $entity->getPipeline()->getTargetField();++ $fieldDefs = $this->defs+ ->getEntity($targetEntityType)+ ->getField($field);++ return $this->enumOptionsProvider->get($fieldDefs) ?? [];+ }+}diff --git a/application/Espo/Modules/Crm/Entities/Opportunity.php b/application/Espo/Modules/Crm/Entities/Opportunity.phpindex 4c171971f1..7c9aa8b81e 100644--- a/application/Espo/Modules/Crm/Entities/Opportunity.php+++ b/application/Espo/Modules/Crm/Entities/Opportunity.php@@ -41,6 +41,13 @@ class Opportunity extends Entity{public const ENTITY_TYPE = 'Opportunity';+ /** @since 9.4.0 */+ public const string FIELD_CLOSED_DATE = 'closeDate';+ /** @since 9.4.0 */+ public const string FIELD_STAGE = 'stage';+ /** @since 9.4.0 */+ public const string FIELD_AMOUNT = 'amount';+public const STAGE_CLOSED_WON = 'Closed Won';public const STAGE_CLOSED_LOST = 'Closed Lost';@@ -69,12 +76,12 @@ class Opportunity extends Entitypublic function getAmount(): ?Currency{/** @var ?Currency */- return $this->getValueObject('amount');+ return $this->getValueObject(self::FIELD_AMOUNT);}public function setAmount(?Currency $amount): self{- $this->setValueObject('amount', $amount);+ $this->setValueObject(self::FIELD_AMOUNT, $amount);return $this;}@@ -82,24 +89,24 @@ class Opportunity extends Entitypublic function getCloseDate(): ?Date{/** @var ?Date */- return $this->getValueObject('closeDate');+ return $this->getValueObject(self::FIELD_CLOSED_DATE);}public function setCloseDate(?Date $closeDate): self{- $this->setValueObject('closeDate', $closeDate);+ $this->setValueObject(self::FIELD_CLOSED_DATE, $closeDate);return $this;}public function getStage(): ?string{- return $this->get('stage');+ return $this->get(self::FIELD_STAGE);}public function setStage(?string $stage): void{- $this->set('stage', $stage);+ $this->set(self::FIELD_STAGE, $stage);}public function getLastStage(): ?stringdiff --git a/application/Espo/Modules/Crm/Resources/metadata/app/entityManagerParams.json b/application/Espo/Modules/Crm/Resources/metadata/app/entityManagerParams.jsonindex 1f6181e4ca..9d3de214c3 100644--- a/application/Espo/Modules/Crm/Resources/metadata/app/entityManagerParams.json+++ b/application/Espo/Modules/Crm/Resources/metadata/app/entityManagerParams.json@@ -135,6 +135,14 @@},"groupIndex": 1},+ "pipelines": {+ "location": "scopes",+ "fieldDefs": {+ "type": "bool",+ "tooltip": true+ },+ "groupIndex": 1+ },"lockable": {"location": "scopes","fieldDefs": {@@ -169,6 +177,14 @@},"groupIndex": 1},+ "pipelines": {+ "location": "scopes",+ "fieldDefs": {+ "type": "bool",+ "tooltip": true+ },+ "groupIndex": 1+ },"lockable": {"location": "scopes","fieldDefs": {diff --git a/application/Espo/Resources/i18n/en_US/Admin.json b/application/Espo/Resources/i18n/en_US/Admin.jsonindex b46d8166ae..3445e2b05d 100644--- a/application/Espo/Resources/i18n/en_US/Admin.json+++ b/application/Espo/Resources/i18n/en_US/Admin.json@@ -87,6 +87,7 @@"Fail": "Fail","Configuration Instructions": "Configuration Instructions","Formula Sandbox": "Formula Sandbox",+ "Pipelines": "Pipelines","is recommended": "is recommended","extension is missing": "extension is missing"},@@ -253,6 +254,7 @@"rebuildRequired": "Rebuild is required"},"messages": {+ "noPipelinesEnabled": "No entity types have pipelines enabled.","cacheIsDisabled": "Cache is disabled, the application will run slow. Enable cache in the [settings](#Admin/settings).","formulaFunctions": "More functions can be found in [documentation]({documentationUrl}).","rebuildRequired": "You need to run rebuild from CLI.",@@ -328,7 +330,8 @@"pdfTemplates": "Templates for printing to PDF.","formulaSandbox": "Write and test formula scripts.","addressCountries": "Countries available for address fields.",- "oAuthProviders": "OAuth providers for integrations."+ "oAuthProviders": "OAuth providers for integrations.",+ "pipelines": "Configure multiple pipelines."},"keywords": {"settings": "system",diff --git a/application/Espo/Resources/i18n/en_US/EntityManager.json b/application/Espo/Resources/i18n/en_US/EntityManager.jsonindex 7e66396ede..11590c3f30 100644--- a/application/Espo/Resources/i18n/en_US/EntityManager.json+++ b/application/Espo/Resources/i18n/en_US/EntityManager.json@@ -58,7 +58,8 @@"aclAccountLink": "ACL Account Link","categories": "Categories","lockable": "Lockable",- "transactionalSave": "Transactional Save"+ "transactionalSave": "Transactional Save",+ "pipelines": "Pipelines"},"options": {"type": {@@ -98,9 +99,12 @@"linkAlreadyExists": "Link name conflict.","linkConflict": "Name conflict: link or field with the same name already exists.","beforeSaveCustomScript": "A script called every time before an entity is saved. Use for setting calculated fields.",- "beforeSaveApiScript": "A script called on create and update API requests before an entity is saved. Use for custom validation and duplicate checking."+ "beforeSaveApiScript": "A script called on create and update API requests before an entity is saved. Use for custom validation and duplicate checking.",+ "cannotEnablePipelinesWithNoStatusField": "Pipelines cannot be enabled as the entity type does not have a status field. Create an Enum field for status if needed, then select it in the Status Field parameter.",+ "cannotEnableCategoriesWithKanbanViewMode": "Categories is not compatible with the Kanban view. Disable either one or another."},"tooltips": {+ "pipelines": "Enables multiple pipelines. Pipelines can be configured at Administration > Pipelines.","transactionalSave": "Record saves and removals will be wrapped into DB transactions.","lockable": "Enables the ability to lock records.","categories": "Enable the category tree feature. Records can be placed into categories.",diff --git a/application/Espo/Resources/i18n/en_US/Global.json b/application/Espo/Resources/i18n/en_US/Global.jsonindex dd1efdf5ca..ac5f229f74 100644--- a/application/Espo/Resources/i18n/en_US/Global.json+++ b/application/Espo/Resources/i18n/en_US/Global.json@@ -70,7 +70,9 @@"OAuthAccount": "OAuth Account","OpenApi": "OpenAPI","CurrencyRecord": "Currency Record",- "CurrencyRecordRate": "Currency Rate"+ "CurrencyRecordRate": "Currency Rate",+ "Pipeline": "Pipeline",+ "PipelineStage": "Pipeline Stage"},"scopeNamesPlural": {"Note": "Notes",@@ -131,7 +133,9 @@"OAuthAccount": "OAuth Accounts","OpenApi": "OpenAPI","CurrencyRecord": "Currencies",- "CurrencyRecordRate": "Currency Rates"+ "CurrencyRecordRate": "Currency Rates",+ "Pipeline": "Pipelines",+ "PipelineStage": "Pipeline Stages"},"labels": {"Previous Page": "Previous Page",@@ -342,6 +346,7 @@"Assigned": "Assigned"},"messages": {+ "cannotRemoveUsed": "Cannot remove the record as it is used.","checkLogsForDetails": "Check logs for details.","pleaseWait": "Please wait...","loading": "Loading...",@@ -465,7 +470,8 @@"massLockDone": "{count} locked","massUnlockDone": "{count} unlocked","cannotModifyLockedRecord": "Cannot modify the field *{field}*. The record is locked.",- "cannotRemoveLockedRecord": "Cannot remove a locked record."+ "cannotRemoveLockedRecord": "Cannot remove a locked record.",+ "noPipeline": "No pipeline."},"boolFilters": {"onlyMy": "Only My",@@ -538,7 +544,9 @@"targetListIsOptedOut": "Is Opted Out (Target List)","childList": "Child List","category": "Category",- "isLocked": "Locked"+ "isLocked": "Locked",+ "pipeline": "Pipeline",+ "pipelineStage": "Pipeline Stage"},"links": {"assignedUser": "Assigned User",@@ -552,7 +560,9 @@"users": "Users","parent": "Parent","children": "Children",- "category": "Category"+ "category": "Category",+ "pipeline": "Pipeline",+ "pipelineStage": "Pipeline Stage"},"dashlets": {"Stream": "Stream",diff --git a/application/Espo/Resources/i18n/en_US/Pipeline.json b/application/Espo/Resources/i18n/en_US/Pipeline.jsonnew file mode 100644index 0000000000..323e084026--- /dev/null+++ b/application/Espo/Resources/i18n/en_US/Pipeline.json@@ -0,0 +1,22 @@+{+ "labels": {+ "Create Pipeline": "Create Pipeline"+ },+ "fields": {+ "order": "Order",+ "status": "Status",+ "entityType": "Entity Type",+ "field": "Field",+ "isAvailableForAll": "Available for All",+ "color": "Color"+ },+ "links": {+ "stages": "Stages"+ },+ "options": {+ "status": {+ "Active": "Active",+ "Inactive": "Inactive"+ }+ }+}diff --git a/application/Espo/Resources/i18n/en_US/PipelineStage.json b/application/Espo/Resources/i18n/en_US/PipelineStage.jsonnew file mode 100644index 0000000000..f19acd5e8b--- /dev/null+++ b/application/Espo/Resources/i18n/en_US/PipelineStage.json@@ -0,0 +1,13 @@+{+ "labels": {+ "Create PipelineStage": "Create Stage"+ },+ "fields": {+ "order": "Order",+ "pipeline": "Pipeline",+ "mappedStatus": "Mapped Status"+ },+ "links": {+ "pipeline": "Pipeline"+ }+}diff --git a/application/Espo/Resources/layouts/Pipeline/bottomPanelsDetail.json b/application/Espo/Resources/layouts/Pipeline/bottomPanelsDetail.jsonnew file mode 100644index 0000000000..a27de9c0ea--- /dev/null+++ b/application/Espo/Resources/layouts/Pipeline/bottomPanelsDetail.json@@ -0,0 +1,5 @@+{+ "stages": {+ "index": 0+ }+}diff --git a/application/Espo/Resources/layouts/Pipeline/defaultSidePanel.json b/application/Espo/Resources/layouts/Pipeline/defaultSidePanel.jsonnew file mode 100644index 0000000000..5060cd3651--- /dev/null+++ b/application/Espo/Resources/layouts/Pipeline/defaultSidePanel.json@@ -0,0 +1,8 @@+[+ {+ "name": "isAvailableForAll"+ },+ {+ "name": "teams"+ }+]diff --git a/application/Espo/Resources/layouts/Pipeline/detail.json b/application/Espo/Resources/layouts/Pipeline/detail.jsonnew file mode 100644index 0000000000..5b995c0e63--- /dev/null+++ b/application/Espo/Resources/layouts/Pipeline/detail.json@@ -0,0 +1,37 @@+[+ {+ "rows": [+ [+ {+ "name": "name"+ },+ {+ "name": "status"+ }+ ],+ [+ {+ "name": "entityType"+ },+ {+ "name": "field"+ }+ ],+ [+ {+ "name": "color"+ },+ false+ ]+ ]+ },+ {+ "rows": [+ [+ {+ "name": "description"+ }+ ]+ ]+ }+]diff --git a/application/Espo/Resources/layouts/Pipeline/detailSmall.json b/application/Espo/Resources/layouts/Pipeline/detailSmall.jsonnew file mode 100644index 0000000000..5b995c0e63--- /dev/null+++ b/application/Espo/Resources/layouts/Pipeline/detailSmall.json@@ -0,0 +1,37 @@+[+ {+ "rows": [+ [+ {+ "name": "name"+ },+ {+ "name": "status"+ }+ ],+ [+ {+ "name": "entityType"+ },+ {+ "name": "field"+ }+ ],+ [+ {+ "name": "color"+ },+ false+ ]+ ]+ },+ {+ "rows": [+ [+ {+ "name": "description"+ }+ ]+ ]+ }+]diff --git a/application/Espo/Resources/layouts/Pipeline/list.json b/application/Espo/Resources/layouts/Pipeline/list.jsonnew file mode 100644index 0000000000..b1f7982782--- /dev/null+++ b/application/Espo/Resources/layouts/Pipeline/list.json@@ -0,0 +1,28 @@+[+ {+ "name": "name",+ "link": true,+ "notSortable": true+ },+ {+ "name": "color",+ "widthPx": 40,+ "noLabel": true,+ "notSortable": true+ },+ {+ "name": "status",+ "width": 18,+ "notSortable": true+ },+ {+ "name": "entityType",+ "width": 18,+ "notSortable": true+ },+ {+ "name": "field",+ "width": 18,+ "notSortable": true+ }+]diff --git a/application/Espo/Resources/layouts/Pipeline/listSmall.json b/application/Espo/Resources/layouts/Pipeline/listSmall.jsonnew file mode 100644index 0000000000..f5157eeb69--- /dev/null+++ b/application/Espo/Resources/layouts/Pipeline/listSmall.json@@ -0,0 +1,18 @@+[+ {+ "name": "name",+ "link": true,+ "notSortable": true+ },+ {+ "name": "color",+ "widthPx": 40,+ "noLabel": true,+ "notSortable": true+ },+ {+ "name": "status",+ "width": 50,+ "notSortable": true+ }+]diff --git a/application/Espo/Resources/layouts/PipelineStage/detail.json b/application/Espo/Resources/layouts/PipelineStage/detail.jsonnew file mode 100644index 0000000000..fde59f1693--- /dev/null+++ b/application/Espo/Resources/layouts/PipelineStage/detail.json@@ -0,0 +1,29 @@+[+ {+ "rows": [+ [+ {+ "name": "name"+ },+ {+ "name": "pipeline"+ }+ ],+ [+ {+ "name": "mappedStatus"+ },+ false+ ]+ ]+ },+ {+ "rows": [+ [+ {+ "name": "description"+ }+ ]+ ]+ }+]diff --git a/application/Espo/Resources/layouts/PipelineStage/detailSmall.json b/application/Espo/Resources/layouts/PipelineStage/detailSmall.jsonnew file mode 100644index 0000000000..fde59f1693--- /dev/null+++ b/application/Espo/Resources/layouts/PipelineStage/detailSmall.json@@ -0,0 +1,29 @@+[+ {+ "rows": [+ [+ {+ "name": "name"+ },+ {+ "name": "pipeline"+ }+ ],+ [+ {+ "name": "mappedStatus"+ },+ false+ ]+ ]+ },+ {+ "rows": [+ [+ {+ "name": "description"+ }+ ]+ ]+ }+]diff --git a/application/Espo/Resources/layouts/PipelineStage/filters.json b/application/Espo/Resources/layouts/PipelineStage/filters.jsonnew file mode 100644index 0000000000..7224eb1525--- /dev/null+++ b/application/Espo/Resources/layouts/PipelineStage/filters.json@@ -0,0 +1,3 @@+[+ "pipeline"+]diff --git a/application/Espo/Resources/layouts/PipelineStage/list.json b/application/Espo/Resources/layouts/PipelineStage/list.jsonnew file mode 100644index 0000000000..fab8afa619--- /dev/null+++ b/application/Espo/Resources/layouts/PipelineStage/list.json@@ -0,0 +1,14 @@+[+ {+ "name": "name",+ "link": true+ },+ {+ "name": "pipeline",+ "width": 30+ },+ {+ "name": "mappedStatus",+ "width": 30+ }+]diff --git a/application/Espo/Resources/layouts/PipelineStage/listForPipeline.json b/application/Espo/Resources/layouts/PipelineStage/listForPipeline.jsonnew file mode 100644index 0000000000..d770faa141--- /dev/null+++ b/application/Espo/Resources/layouts/PipelineStage/listForPipeline.json@@ -0,0 +1,12 @@+[+ {+ "name": "name",+ "link": true,+ "notSortable": true+ },+ {+ "name": "mappedStatus",+ "width": 40,+ "notSortable": true+ }+]diff --git a/application/Espo/Resources/layouts/PipelineStage/listSmall.json b/application/Espo/Resources/layouts/PipelineStage/listSmall.jsonnew file mode 100644index 0000000000..ad6cf00d5f--- /dev/null+++ b/application/Espo/Resources/layouts/PipelineStage/listSmall.json@@ -0,0 +1,14 @@+[+ {+ "name": "name",+ "link": true+ },+ {+ "name": "pipeline",+ "width": 33+ },+ {+ "name": "mappedStatus",+ "width": 25+ }+]diff --git a/application/Espo/Resources/metadata/aclDefs/Pipeline.json b/application/Espo/Resources/metadata/aclDefs/Pipeline.jsonnew file mode 100644index 0000000000..504404173d--- /dev/null+++ b/application/Espo/Resources/metadata/aclDefs/Pipeline.json@@ -0,0 +1,4 @@+{+ "accessCheckerClassName": "Espo\\Classes\\Acl\\Pipeline\\AccessChecker",+ "portalAccessCheckerClassName": "Espo\\Classes\\AclPortal\\Pipeline\\AccessChecker"+}diff --git a/application/Espo/Resources/metadata/aclDefs/PipelineStage.json b/application/Espo/Resources/metadata/aclDefs/PipelineStage.jsonnew file mode 100644index 0000000000..6bd7d5b7b5--- /dev/null+++ b/application/Espo/Resources/metadata/aclDefs/PipelineStage.json@@ -0,0 +1,4 @@+{+ "accessCheckerClassName": "Espo\\Classes\\Acl\\PipelineStage\\AccessChecker",+ "portalAccessCheckerClassName": "Espo\\Classes\\AclPortal\\PipelineStage\\AccessChecker"+}diff --git a/application/Espo/Resources/metadata/app/acl.json b/application/Espo/Resources/metadata/app/acl.jsonindex 507030f5e7..3c89dcf96e 100644--- a/application/Espo/Resources/metadata/app/acl.json+++ b/application/Espo/Resources/metadata/app/acl.json@@ -65,7 +65,9 @@"WorkingTimeRange": "WorkingTimeCalendar","Stream": true,"CurrencyRecord": "boolean:Currency",- "CurrencyRecordRate": "Currency"+ "CurrencyRecordRate": "Currency",+ "Pipeline": true,+ "PipelineStage": true},"fieldLevel": {},@@ -161,7 +163,9 @@"CurrencyRecordRate": {"read": "yes","edit": "yes"- }+ },+ "Pipeline": true,+ "PipelineStage": true}},"valuePermissionList": [diff --git a/application/Espo/Resources/metadata/app/aclPortal.json b/application/Espo/Resources/metadata/app/aclPortal.jsonindex 0114e9aa3a..40652d57a9 100644--- a/application/Espo/Resources/metadata/app/aclPortal.json+++ b/application/Espo/Resources/metadata/app/aclPortal.json@@ -43,7 +43,9 @@"edit": "own","delete": "no","create": "no"- }+ },+ "Pipeline": true,+ "PipelineStage": true},"fieldLevel": {},diff --git a/application/Espo/Resources/metadata/app/adminPanel.json b/application/Espo/Resources/metadata/app/adminPanel.jsonindex 22e63bb6a6..5aa367b39a 100644--- a/application/Espo/Resources/metadata/app/adminPanel.json+++ b/application/Espo/Resources/metadata/app/adminPanel.json@@ -359,6 +359,12 @@"iconClass": "fas fa-sign-in-alt","description": "oAuthProviders"},+ {+ "url": "#Admin/pipelines",+ "label": "Pipelines",+ "iconClass": "fas fa-timeline",+ "description": "pipelines"+ },{"url": "#Admin/appLog","label": "App Log",diff --git a/application/Espo/Resources/metadata/app/appParams.json b/application/Espo/Resources/metadata/app/appParams.jsonindex 0f7e8b4162..eda0b2562b 100644--- a/application/Espo/Resources/metadata/app/appParams.json+++ b/application/Espo/Resources/metadata/app/appParams.json@@ -10,5 +10,8 @@},"currencyRates": {"className": "Espo\\Classes\\AppParams\\CurrencyRates"+ },+ "pipelines": {+ "className": "Espo\\Classes\\AppParams\\Pipelines"}}diff --git a/application/Espo/Resources/metadata/app/entityManager.json b/application/Espo/Resources/metadata/app/entityManager.jsonindex 184bad5677..f872941134 100644--- a/application/Espo/Resources/metadata/app/entityManager.json+++ b/application/Espo/Resources/metadata/app/entityManager.json@@ -9,11 +9,16 @@"Espo\\Tools\\EntityManager\\Hook\\Hooks\\DeleteHasChildrenLinks","Espo\\Tools\\EntityManager\\Hook\\Hooks\\CategoriesDeleteHook"],+ "beforeUpdateHookClassNameList": [+ "Espo\\Tools\\EntityManager\\Hook\\Hooks\\CategoriesBeforeUpdateHook",+ "Espo\\Tools\\EntityManager\\Hook\\Hooks\\PipelinesBeforeUpdateHook"+ ],"updateHookClassNameList": ["Espo\\Tools\\EntityManager\\Hook\\Hooks\\AssignedUsersUpdateHook","Espo\\Tools\\EntityManager\\Hook\\Hooks\\CollaboratorsUpdateHook","Espo\\Tools\\EntityManager\\Hook\\Hooks\\StreamUpdateHook","Espo\\Tools\\EntityManager\\Hook\\Hooks\\CategoriesUpdateHook",- "Espo\\Tools\\EntityManager\\Hook\\Hooks\\LockableUpdateHook"+ "Espo\\Tools\\EntityManager\\Hook\\Hooks\\LockableUpdateHook",+ "Espo\\Tools\\EntityManager\\Hook\\Hooks\\PipelinesUpdateHook"]}diff --git a/application/Espo/Resources/metadata/app/entityManagerParams.json b/application/Espo/Resources/metadata/app/entityManagerParams.jsonindex 7f2bfbacf1..05328659db 100644--- a/application/Espo/Resources/metadata/app/entityManagerParams.json+++ b/application/Espo/Resources/metadata/app/entityManagerParams.json@@ -56,6 +56,14 @@},"groupIndex": 1},+ "pipelines": {+ "location": "scopes",+ "fieldDefs": {+ "type": "bool",+ "tooltip": true+ },+ "groupIndex": 1+ },"aclContactLink": {"location": "aclDefs","param": "contactLink",@@ -127,6 +135,14 @@},"groupIndex": 1},+ "pipelines": {+ "location": "scopes",+ "fieldDefs": {+ "type": "bool",+ "tooltip": true+ },+ "groupIndex": 1+ },"aclContactLink": {"location": "aclDefs","param": "contactLink",@@ -198,6 +214,14 @@},"groupIndex": 1},+ "pipelines": {+ "location": "scopes",+ "fieldDefs": {+ "type": "bool",+ "tooltip": true+ },+ "groupIndex": 1+ },"aclContactLink": {"location": "aclDefs","param": "contactLink",@@ -277,6 +301,14 @@},"groupIndex": 1},+ "pipelines": {+ "location": "scopes",+ "fieldDefs": {+ "type": "bool",+ "tooltip": true+ },+ "groupIndex": 1+ },"aclContactLink": {"location": "aclDefs","param": "contactLink",diff --git a/application/Espo/Resources/metadata/app/metadata.json b/application/Espo/Resources/metadata/app/metadata.jsonindex 4994af9be9..62f08960e4 100644--- a/application/Espo/Resources/metadata/app/metadata.json+++ b/application/Espo/Resources/metadata/app/metadata.json@@ -53,6 +53,7 @@"Espo\\Core\\Utils\\Metadata\\AdditionalBuilder\\DeleteIdField","Espo\\Core\\Utils\\Metadata\\AdditionalBuilder\\DisableAssignedUser","Espo\\Core\\Utils\\Metadata\\AdditionalBuilder\\StreamUpdatedAtField",+ "Espo\\Core\\Utils\\Metadata\\AdditionalBuilder\\Pipelines","Espo\\Core\\Utils\\Metadata\\AdditionalBuilder\\LogicDefsBc"]}diff --git a/application/Espo/Resources/metadata/clientDefs/Global.json b/application/Espo/Resources/metadata/clientDefs/Global.jsonindex 2ad179b07f..3b569149d5 100644--- a/application/Espo/Resources/metadata/clientDefs/Global.json+++ b/application/Espo/Resources/metadata/clientDefs/Global.json@@ -61,10 +61,12 @@},"viewSetupHandlers": {"record/detail": [- "handlers/record/lock-view-setup"+ "handlers/record/lock-view-setup",+ "handlers/record/pipeline-view-setup"],"record/edit": [- "handlers/record/lock-view-setup"+ "handlers/record/lock-view-setup",+ "handlers/record/pipeline-view-setup"]}}diff --git a/application/Espo/Resources/metadata/clientDefs/Pipeline.json b/application/Espo/Resources/metadata/clientDefs/Pipeline.jsonnew file mode 100644index 0000000000..1ab7857342--- /dev/null+++ b/application/Espo/Resources/metadata/clientDefs/Pipeline.json@@ -0,0 +1,49 @@+{+ "controller": "controllers/record",+ "massRemoveDisabled": true,+ "massUpdateDisabled": true,+ "mergeDisabled": true,+ "rowActionList": [+ "moveUp",+ "moveDown"+ ],+ "views": {+ "detail": "views/pipeline/detail"+ },+ "rowActionDefs": {+ "moveUp": {+ "label": "Move Up",+ "groupIndex": 3,+ "handler": "handlers/pipeline/move-row-action",+ "acl": "edit"+ },+ "moveDown": {+ "label": "Move Down",+ "groupIndex": 3,+ "handler": "handlers/pipeline/move-row-action",+ "acl": "edit"+ }+ },+ "relationshipPanels": {+ "stages": {+ "view": "views/pipeline/record/panels/stages",+ "selectDisabled": true,+ "unlinkDisabled": true,+ "layout": "listForPipeline",+ "rowActionList": [+ "moveUp",+ "moveDown"+ ],+ "createAttributeMap": {+ "entityType": "entityType",+ "field": "field"+ },+ "orderBy": "order",+ "orderDirection": "asc",+ "mandatoryAttributeList": [+ "entityType",+ "field"+ ]+ }+ }+}diff --git a/application/Espo/Resources/metadata/clientDefs/PipelineStage.json b/application/Espo/Resources/metadata/clientDefs/PipelineStage.jsonnew file mode 100644index 0000000000..2a2035411a--- /dev/null+++ b/application/Espo/Resources/metadata/clientDefs/PipelineStage.json@@ -0,0 +1,19 @@+{+ "controller": "controllers/record",+ "createDisabled": true,+ "massRemoveDisabled": true,+ "massUpdateDisabled": true,+ "mergeDisabled": true,+ "rowActionDefs": {+ "moveUp": {+ "label": "Move Up",+ "groupIndex": 3,+ "handler": "handlers/pipeline-stage/move-row-action"+ },+ "moveDown": {+ "label": "Move Down",+ "groupIndex": 3,+ "handler": "handlers/pipeline-stage/move-row-action"+ }+ }+}diff --git a/application/Espo/Resources/metadata/entityDefs/Pipeline.json b/application/Espo/Resources/metadata/entityDefs/Pipeline.jsonnew file mode 100644index 0000000000..dea73fa491--- /dev/null+++ b/application/Espo/Resources/metadata/entityDefs/Pipeline.json@@ -0,0 +1,119 @@+{+ "fields": {+ "name": {+ "type": "varchar",+ "required": true,+ "maxLength": 100,+ "duplicateIgnore": true+ },+ "order": {+ "type": "int",+ "readOnly": true,+ "duplicateIgnore": true+ },+ "status": {+ "type": "enum",+ "maxLength": 8,+ "options": [+ "Active",+ "Inactive"+ ],+ "default": "Active",+ "style": {+ "Inactive": "info"+ },+ "duplicateIgnore": true+ },+ "entityType": {+ "type": "enum",+ "maxLength": 100,+ "required": true,+ "readOnlyAfterCreate": true,+ "view": "views/pipeline/fields/entity-type",+ "validatorClassNameList": [+ "Espo\\Classes\\FieldValidators\\Pipeline\\EntityType\\Valid"+ ]+ },+ "field": {+ "type": "enum",+ "maxLength": 100,+ "readOnly": true,+ "validatorClassNameList": [+ "Espo\\Classes\\FieldValidators\\Pipeline\\Field\\Valid"+ ],+ "view": "views/pipeline/fields/field"+ },+ "color": {+ "type": "int",+ "min": 0,+ "max": 8,+ "view": "views/fields/color"+ },+ "isAvailableForAll": {+ "type": "bool",+ "default": true+ },+ "description": {+ "type": "text"+ },+ "teams": {+ "type": "linkMultiple",+ "view": "views/fields/teams"+ },+ "createdAt": {+ "type": "datetime",+ "readOnly": true+ },+ "modifiedAt": {+ "type": "datetime",+ "readOnly": true+ },+ "createdBy": {+ "type": "link",+ "readOnly": true,+ "view": "views/fields/user"+ },+ "modifiedBy": {+ "type": "link",+ "readOnly": true,+ "view": "views/fields/user"+ }+ },+ "links": {+ "stages": {+ "type": "hasMany",+ "entity": "PipelineStage",+ "foreign": "pipeline",+ "readOnly": true,+ "cascadeRemoval": true,+ "orderBy": "order",+ "order": "asc"+ },+ "teams": {+ "type": "hasMany",+ "entity": "Team",+ "relationName": "entityTeam",+ "readOnly": true+ },+ "createdBy": {+ "type": "belongsTo",+ "entity": "User"+ },+ "modifiedBy": {+ "type": "belongsTo",+ "entity": "User"+ }+ },+ "collection": {+ "orderBy": "order",+ "order": "asc"+ },+ "indexes": {+ "entityTypeStatus": {+ "columns": [+ "entityType",+ "status"+ ]+ }+ }+}diff --git a/application/Espo/Resources/metadata/entityDefs/PipelineStage.json b/application/Espo/Resources/metadata/entityDefs/PipelineStage.jsonnew file mode 100644index 0000000000..30a9e4e431--- /dev/null+++ b/application/Espo/Resources/metadata/entityDefs/PipelineStage.json@@ -0,0 +1,80 @@+{+ "fields": {+ "name": {+ "type": "varchar",+ "maxLength": 50,+ "required": true+ },+ "pipeline": {+ "type": "link",+ "readOnlyAfterCreate": true,+ "required": true+ },+ "order": {+ "type": "int",+ "readOnly": true+ },+ "mappedStatus": {+ "type": "enum",+ "maxLength": 100,+ "readOnlyAfterCreate": true,+ "required": true,+ "view": "views/pipeline-stage/fields/mapped-status",+ "validatorClassNameList": [+ "Espo\\Classes\\FieldValidators\\PipelineStatus\\MappedStatus\\Valid"+ ]+ },+ "entityType": {+ "type": "foreign",+ "link": "pipeline",+ "field": "entityType"+ },+ "field": {+ "type": "foreign",+ "link": "pipeline",+ "field": "field"+ },+ "description": {+ "type": "text"+ },+ "createdAt": {+ "type": "datetime",+ "readOnly": true+ },+ "modifiedAt": {+ "type": "datetime",+ "readOnly": true+ },+ "createdBy": {+ "type": "link",+ "readOnly": true,+ "view": "views/fields/user",+ "fieldManagerParamList": []+ },+ "modifiedBy": {+ "type": "link",+ "readOnly": true,+ "view": "views/fields/user",+ "fieldManagerParamList": []+ }+ },+ "links": {+ "pipeline": {+ "type": "belongsTo",+ "entity": "Pipeline",+ "foreign": "stages"+ },+ "createdBy": {+ "type": "belongsTo",+ "entity": "User"+ },+ "modifiedBy": {+ "type": "belongsTo",+ "entity": "User"+ }+ },+ "collection": {+ "orderBy": "listOrder",+ "order": "asc"+ }+}diff --git a/application/Espo/Resources/metadata/logicDefs/Pipeline.json b/application/Espo/Resources/metadata/logicDefs/Pipeline.jsonnew file mode 100644index 0000000000..99bc902b6a--- /dev/null+++ b/application/Espo/Resources/metadata/logicDefs/Pipeline.json@@ -0,0 +1,14 @@+{+ "fields": {+ "teams": {+ "visible": {+ "conditionGroup": [+ {+ "type": "isFalse",+ "attribute": "isAvailableForAll"+ }+ ]+ }+ }+ }+}diff --git a/application/Espo/Resources/metadata/recordDefs/Pipeline.json b/application/Espo/Resources/metadata/recordDefs/Pipeline.jsonnew file mode 100644index 0000000000..387a224003--- /dev/null+++ b/application/Espo/Resources/metadata/recordDefs/Pipeline.json@@ -0,0 +1,28 @@+{+ "beforeDeleteHookClassNameList": [+ "Espo\\Classes\\Record\\Hooks\\Pipeline\\BeforeDelete"+ ],+ "afterCreateHookClassNameList": [+ "Espo\\Classes\\Record\\Hooks\\Pipeline\\AfterSave"+ ],+ "afterUpdateHookClassNameList": [+ "Espo\\Classes\\Record\\Hooks\\Pipeline\\AfterSave"+ ],+ "afterDeleteHookClassNameList": [+ "Espo\\Classes\\Record\\Hooks\\Pipeline\\AfterDelete"+ ],+ "massActions": {+ "delete": {+ "disabled": true+ },+ "update": {+ "disabled": true+ }+ },+ "actions": {+ "merge": {+ "disabled": true+ }+ },+ "duplicateWhereBuilderClassName": "Espo\\Classes\\DuplicateWhereBuilders\\General"+}diff --git a/application/Espo/Resources/metadata/recordDefs/PipelineStage.json b/application/Espo/Resources/metadata/recordDefs/PipelineStage.jsonnew file mode 100644index 0000000000..28ae1364f8--- /dev/null+++ b/application/Espo/Resources/metadata/recordDefs/PipelineStage.json@@ -0,0 +1,24 @@+{+ "afterCreateHookClassNameList": [+ "Espo\\Classes\\Record\\Hooks\\PipelineStage\\AfterSave"+ ],+ "afterUpdateHookClassNameList": [+ "Espo\\Classes\\Record\\Hooks\\PipelineStage\\AfterSave"+ ],+ "afterDeleteHookClassNameList": [+ "Espo\\Classes\\Record\\Hooks\\PipelineStage\\AfterDelete"+ ],+ "massActions": {+ "delete": {+ "disabled": true+ },+ "update": {+ "disabled": true+ }+ },+ "actions": {+ "merge": {+ "disabled": true+ }+ }+}diff --git a/application/Espo/Resources/metadata/scopes/Pipeline.json b/application/Espo/Resources/metadata/scopes/Pipeline.jsonnew file mode 100644index 0000000000..56843117cc--- /dev/null+++ b/application/Espo/Resources/metadata/scopes/Pipeline.json@@ -0,0 +1,9 @@+{+ "entity": true,+ "importable": true,+ "statusField": "status",+ "exportFormatList": ["csv"],+ "duplicateCheckFieldList": [+ "name"+ ]+}diff --git a/application/Espo/Resources/metadata/scopes/PipelineStage.json b/application/Espo/Resources/metadata/scopes/PipelineStage.jsonnew file mode 100644index 0000000000..7365550e41--- /dev/null+++ b/application/Espo/Resources/metadata/scopes/PipelineStage.json@@ -0,0 +1,5 @@+{+ "entity": true,+ "importable": true,+ "exportFormatList": ["csv"]+}diff --git a/application/Espo/Resources/metadata/selectDefs/Pipeline.json b/application/Espo/Resources/metadata/selectDefs/Pipeline.jsonnew file mode 100644index 0000000000..32dc278286--- /dev/null+++ b/application/Espo/Resources/metadata/selectDefs/Pipeline.json@@ -0,0 +1,9 @@+{+ "primaryFilterClassNameMap": {+ "active": "Espo\\Classes\\Select\\Pipeline\\PrimaryFilters\\Active"+ },+ "accessControlFilterClassNameMap": {+ "mandatory": "Espo\\Classes\\Select\\Pipeline\\AccessControlFilters\\Mandatory"+ },+ "accessControlFilterResolverClassName": "Espo\\Core\\Select\\AccessControl\\FilterResolvers\\Boolean"+}diff --git a/application/Espo/Resources/metadata/selectDefs/PipelineStage.json b/application/Espo/Resources/metadata/selectDefs/PipelineStage.jsonnew file mode 100644index 0000000000..4381c64f62--- /dev/null+++ b/application/Espo/Resources/metadata/selectDefs/PipelineStage.json@@ -0,0 +1,9 @@+{+ "accessControlFilterClassNameMap": {+ "mandatory": "Espo\\Classes\\Select\\PipelineStage\\AccessControlFilters\\Mandatory"+ },+ "accessControlFilterResolverClassName": "Espo\\Core\\Select\\AccessControl\\FilterResolvers\\Boolean",+ "ordererClassNameMap": {+ "listOrder": "Espo\\Classes\\Select\\PipelineStage\\ListOrderOrderer"+ }+}diff --git a/application/Espo/Resources/routes.json b/application/Espo/Resources/routes.jsonindex 455920b1b3..0fa01f87e4 100644--- a/application/Espo/Resources/routes.json+++ b/application/Espo/Resources/routes.json@@ -694,5 +694,15 @@"id": ":id","link": ":link"}+ },+ {+ "route": "Pipeline/:id/move/:type",+ "method": "post",+ "actionClassName": "Espo\\Tools\\Pipeline\\Api\\PostMove"+ },+ {+ "route": "PipelineStage/:id/move/:type",+ "method": "post",+ "actionClassName": "Espo\\Tools\\Pipeline\\Api\\PostStageMove"}]diff --git a/application/Espo/Tools/EntityManager/Hook/Hooks/CategoriesBeforeUpdateHook.php b/application/Espo/Tools/EntityManager/Hook/Hooks/CategoriesBeforeUpdateHook.phpnew file mode 100644index 0000000000..ae33f5d38e--- /dev/null+++ b/application/Espo/Tools/EntityManager/Hook/Hooks/CategoriesBeforeUpdateHook.php@@ -0,0 +1,53 @@+<?php+/************************************************************************+ * This file is part of EspoCRM.+ *+ * EspoCRM – Open Source CRM application.+ * Copyright (C) 2014-2026 EspoCRM, Inc.+ * 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\EntityManager\Hook\Hooks;++use Espo\Core\Exceptions\Conflict;+use Espo\Core\Exceptions\Error\Body;+use Espo\Tools\EntityManager\Hook\UpdateHook;+use Espo\Tools\EntityManager\Params;++/**+ * @noinspection PhpUnused+ */+class CategoriesBeforeUpdateHook implements UpdateHook+{+ private const string PARAM = 'categories';++ public function process(Params $params, Params $previousParams): void+ {+ if ($params->get(self::PARAM) && $params->get('kanbanViewMode')) {+ throw Conflict::createWithBody(+ 'cannotEnableCategoriesWithKanbanViewMode',+ Body::create()->withMessageTranslation('cannotEnableCategoriesWithKanbanViewMode', 'EntityManager')+ );+ }+ }+}diff --git a/application/Espo/Tools/EntityManager/Hook/Hooks/PipelinesBeforeUpdateHook.php b/application/Espo/Tools/EntityManager/Hook/Hooks/PipelinesBeforeUpdateHook.phpnew file mode 100644index 0000000000..e617d9a8f6--- /dev/null+++ b/application/Espo/Tools/EntityManager/Hook/Hooks/PipelinesBeforeUpdateHook.php@@ -0,0 +1,53 @@+<?php+/************************************************************************+ * This file is part of EspoCRM.+ *+ * EspoCRM – Open Source CRM application.+ * Copyright (C) 2014-2026 EspoCRM, Inc.+ * 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\EntityManager\Hook\Hooks;++use Espo\Core\Exceptions\Conflict;+use Espo\Core\Exceptions\Error\Body;+use Espo\Tools\EntityManager\Hook\UpdateHook;+use Espo\Tools\EntityManager\Params;++/**+ * @noinspection PhpUnused+ */+class PipelinesBeforeUpdateHook implements UpdateHook+{+ private const string PARAM = 'pipelines';++ public function process(Params $params, Params $previousParams): void+ {+ if ($params->get(self::PARAM) && !$params->get('statusField')) {+ throw Conflict::createWithBody(+ 'cannotEnablePipelinesWithNoStatusField',+ Body::create()->withMessageTranslation('cannotEnablePipelinesWithNoStatusField', 'EntityManager')+ );+ }+ }+}diff --git a/application/Espo/Tools/EntityManager/Hook/Hooks/PipelinesUpdateHook.php b/application/Espo/Tools/EntityManager/Hook/Hooks/PipelinesUpdateHook.phpnew file mode 100644index 0000000000..b1ed53d12f--- /dev/null+++ b/application/Espo/Tools/EntityManager/Hook/Hooks/PipelinesUpdateHook.php@@ -0,0 +1,185 @@+<?php+/************************************************************************+ * This file is part of EspoCRM.+ *+ * EspoCRM – Open Source CRM application.+ * Copyright (C) 2014-2026 EspoCRM, Inc.+ * 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\EntityManager\Hook\Hooks;++use Espo\Classes\Acl\Common\Pipeline\PipelineLinkChecker;+use Espo\Classes\Acl\Common\Pipeline\PipelineStageLinkChecker;+use Espo\Classes\FieldValidators\Common\PipelineStage\Valid;+use Espo\Core\DataManager;+use Espo\Core\Exceptions\Error;+use Espo\Core\Name\Field;+use Espo\Core\ORM\Type\FieldType;+use Espo\Core\Utils\Log;+use Espo\Core\Utils\Metadata;+use Espo\Entities\Pipeline;+use Espo\Entities\PipelineStage;+use Espo\ORM\Defs\Params\FieldParam;+use Espo\ORM\Type\RelationType;+use Espo\Tools\EntityManager\Hook\UpdateHook;+use Espo\Tools\EntityManager\Params;+use Espo\Tools\LayoutManager\LayoutCustomizer;+use Espo\Tools\LayoutManager\LayoutName;++/**+ * @noinspection PhpUnused+ */+class PipelinesUpdateHook implements UpdateHook+{+ private const string PARAM = 'pipelines';++ public function __construct(+ private Metadata $metadata,+ private DataManager $dataManager,+ private LayoutCustomizer $layoutCustomizer,+ private Log $log,+ ) {}++ public function process(Params $params, Params $previousParams): void+ {+ if ($params->get(self::PARAM) && !$previousParams->get(self::PARAM)) {+ $this->add($params->getName());+ } else if (!$params->get(self::PARAM) && $previousParams->get(self::PARAM)) {+ $this->remove($params->getName());+ }+ }++ /**+ * @throws Error+ */+ private function add(string $entityType): void+ {+ if ($this->metadata->get("entityDefs.$entityType.links." . Field::PIPELINE . ".isCustom")) {+ $this->log->warning("Cannot enable pipelines for $entityType as the link already exists.");++ return;+ }++ $this->metadata->set('entityDefs', $entityType, [+ 'fields' => [+ Field::PIPELINE => [+ FieldParam::TYPE => FieldType::LINK,+ FieldParam::REQUIRED => true,+ 'audited' => true,+ 'inlineEditDisabled' => true,+ 'fieldManagerParamList' => [+ FieldParam::READ_ONLY_AFTER_CREATE,+ 'audited',+ 'tooltipText',+ ],+ 'view' => 'views/fields/extra/pipeline',+ ],+ Field::PIPELINE_STAGE => [+ FieldParam::TYPE => FieldType::LINK,+ FieldParam::REQUIRED => true,+ 'audited' => true,+ 'validationDependsOnFieldList' => [+ Field::PIPELINE,+ ],+ 'validatorClassNameList' => [+ Valid::class,+ ],+ 'fieldManagerParamList' => [+ 'audited',+ 'tooltipText',+ 'inlineEditDisabled',+ ],+ 'view' => 'views/fields/extra/pipeline-stage',+ ],+ ],+ 'links' => [+ Field::PIPELINE => [+ 'type' => RelationType::BELONGS_TO,+ 'entity' => Pipeline::ENTITY_TYPE,+ ],+ Field::PIPELINE_STAGE => [+ 'type' => RelationType::BELONGS_TO,+ 'entity' => PipelineStage::ENTITY_TYPE,+ ],+ ],+ ]);++ $this->metadata->set('aclDefs', $entityType, [+ 'linkCheckerClassNameMap' => [+ Field::PIPELINE => PipelineLinkChecker::class,+ Field::PIPELINE_STAGE => PipelineStageLinkChecker::class,+ ],+ ]);++ $this->metadata->save();+ $this->dataManager->rebuild([$entityType]);++ $this->layoutCustomizer->addDetailField($entityType, Field::PIPELINE, LayoutName::DETAIL);+ $this->layoutCustomizer->addDetailField($entityType, Field::PIPELINE_STAGE, LayoutName::DETAIL);++ $this->layoutCustomizer->addDetailField($entityType, Field::PIPELINE, LayoutName::DETAIL_SMALL);+ $this->layoutCustomizer->addDetailField($entityType, Field::PIPELINE_STAGE, LayoutName::DETAIL_SMALL);+ }++ /**+ * @throws Error+ */+ private function remove(string $entityType): void+ {+ $field = Field::PIPELINE;++ if (+ $this->metadata->get("entityDefs.$entityType.links.$field.isCustom") &&+ $this->metadata->get("entityDefs.$entityType.links.$field.entityType") !== Pipeline::ENTITY_TYPE+ ) {+ return;+ }++ $this->metadata->delete('entityDefs', $entityType, [+ 'fields.' . Field::PIPELINE,+ 'fields.' . Field::PIPELINE_STAGE,+ 'links.' . Field::PIPELINE,+ 'links.' . Field::PIPELINE_STAGE,+ ]);++ $this->metadata->delete('entityAcl', $entityType, [+ 'links.' . Field::PIPELINE,+ 'links.' . Field::PIPELINE_STAGE,+ ]);++ $this->metadata->delete('aclDefs', $entityType, [+ 'linkCheckerClassNameMap.' . Field::PIPELINE,+ 'linkCheckerClassNameMap.' . Field::PIPELINE_STAGE,+ ]);++ $this->metadata->save();+ $this->dataManager->rebuild([$entityType]);++ $this->layoutCustomizer->removeInDetail($entityType, Field::PIPELINE, LayoutName::DETAIL);+ $this->layoutCustomizer->removeInDetail($entityType, Field::PIPELINE_STAGE, LayoutName::DETAIL);++ $this->layoutCustomizer->removeInDetail($entityType, Field::PIPELINE, LayoutName::DETAIL_SMALL);+ $this->layoutCustomizer->removeInDetail($entityType, Field::PIPELINE_STAGE, LayoutName::DETAIL_SMALL);+ }+}diff --git a/application/Espo/Tools/EntityManager/NameUtil.php b/application/Espo/Tools/EntityManager/NameUtil.phpindex f0e900b06b..6e5788ca77 100644--- a/application/Espo/Tools/EntityManager/NameUtil.php+++ b/application/Espo/Tools/EntityManager/NameUtil.php@@ -157,6 +157,8 @@ class NameUtilField::MODIFIED_BY,Field::MODIFIED_AT,Field::IS_LOCKED,+ Field::PIPELINE,+ Field::PIPELINE_STAGE,'emailAddressList','userEmailAddressList',diff --git a/application/Espo/Tools/Kanban/Kanban.php b/application/Espo/Tools/Kanban/Kanban.phpindex 5dd4530caf..1c503dcb07 100644--- a/application/Espo/Tools/Kanban/Kanban.php+++ b/application/Espo/Tools/Kanban/Kanban.php@@ -41,6 +41,9 @@ use Espo\Core\Select\SearchParams;use Espo\Core\Select\SelectBuilderFactory;use Espo\ORM\Entity;use Espo\ORM\EntityManager;+use Espo\Tools\Pipeline\Data\PipelineData;+use Espo\Tools\Pipeline\Data\StageData;+use Espo\Tools\Pipeline\PipelineDataProvider;class Kanban{@@ -53,6 +56,7 @@ class Kanbanprivate ?SearchParams $searchParams = null;private ?string $userId = null;private int $maxOrderNumber = self::DEFAULT_MAX_ORDER_NUMBER;+ private ?string $pipelineId = null;public function __construct(private SelectBuilderFactory $selectBuilderFactory,@@ -61,6 +65,7 @@ class Kanbanprivate RecordServiceContainer $recordServiceContainer,private ApplierClassNameListProvider $applierClassNameListProvider,private MetadataProvider $metadataProvider,+ private PipelineDataProvider $pipelineDataProvider,) {}public function setEntityType(string $entityType): self@@ -77,6 +82,16 @@ class Kanbanreturn $this;}+ /**+ * @since 9.4.0+ */+ public function setPipelineId(?string $pipelineId): self+ {+ $this->pipelineId = $pipelineId;++ return $this;+ }+public function setCountDisabled(bool $countDisabled): self{$this->countDisabled = $countDisabled;@@ -149,24 +164,16 @@ class Kanban->build();$statusField = $this->metadataProvider->getStatusField($this->entityType);- $statusList = $this->metadataProvider->getStatusList($this->entityType);- $statusIgnoreList = $this->metadataProvider->getStatusIgnoreList($this->entityType);-+ $statusList = $this->metadataProvider->getStatusList($this->entityType, $this->pipelineId);$groupList = [];$repository = $this->entityManager->getRDBRepository($this->entityType);$hasMore = false;- foreach ($statusList as $status) {- if (in_array($status, $statusIgnoreList)) {- continue;- }-- if (!$status) {- continue;- }+ $pipeline = $this->getPipelineData($this->entityType);+ foreach ($statusList as $status) {$itemSelectBuilder = $this->entityManager->getQueryBuilder()->select()@@ -236,7 +243,14 @@ class Kanban/** @var Collection<Entity> $itemRecordCollection */$itemRecordCollection = new Collection($collectionSub, $totalSub);- $groupList[] = new GroupItem($status, $itemRecordCollection);+ $stage = $this->getPipelineStageData($pipeline, $status);++ $groupList[] = new GroupItem(+ name: $status,+ collection: $itemRecordCollection,+ label: $stage?->name,+ style: $stage?->style,+ );}$total = !$this->countDisabled ?@@ -245,4 +259,38 @@ class Kanbanreturn new Result($groupList, $total);}++ private function getPipelineData(string $entityType): ?PipelineData+ {+ if (!$this->pipelineId) {+ return null;+ }++ $pipeline = null;++ $pipelines = $this->pipelineDataProvider->get()[$entityType] ?? [];++ foreach ($pipelines as $it) {+ if ($it->id === $this->pipelineId) {+ $pipeline = $it;++ break;+ }+ }++ return $pipeline;+ }++ private function getPipelineStageData(?PipelineData $pipeline, string $id): ?StageData+ {+ if ($pipeline) {+ foreach ($pipeline->stages as $it) {+ if ($it->id === $id) {+ return $it;+ }+ }+ }++ return null;+ }}diff --git a/application/Espo/Tools/Kanban/KanbanService.php b/application/Espo/Tools/Kanban/KanbanService.phpindex 0074ee8abe..7d411c6a28 100644--- a/application/Espo/Tools/Kanban/KanbanService.php+++ b/application/Espo/Tools/Kanban/KanbanService.php@@ -35,11 +35,18 @@ use Espo\Core\Exceptions\BadRequest;use Espo\Core\Exceptions\Error;use Espo\Core\Exceptions\Forbidden;use Espo\Core\Exceptions\ForbiddenSilent;+use Espo\Core\Exceptions\NotFound;use Espo\Core\InjectableFactory;+use Espo\Core\Name\Field;+use Espo\Core\Record\EntityProvider;use Espo\Core\Select\SearchParams;+use Espo\Core\Select\Where\Item\Type;use Espo\Core\Utils\Config;use Espo\Core\Utils\Metadata;+use Espo\Entities\Pipeline;+use Espo\Entities\PipelineStage;use Espo\Entities\User;+use Espo\Tools\Pipeline\MetadataProvider as PipelineMetadataProvider;class KanbanService{@@ -49,13 +56,16 @@ class KanbanServiceprivate InjectableFactory $injectableFactory,private Config $config,private Metadata $metadata,- private Orderer $orderer+ private Orderer $orderer,+ private EntityProvider $entityProvider,+ private PipelineMetadataProvider $pipelineMetadata,) {}/*** @throws Error* @throws Forbidden* @throws BadRequest+ * @throws NotFound*/public function getData(string $entityType, SearchParams $searchParams): Result{@@ -69,9 +79,12 @@ class KanbanService$maxOrderNumber = $this->config->get('kanbanMaxOrderNumber');+ $pipeline = $this->getPipeline($entityType, $searchParams);+return $this->createKanban()->setEntityType($entityType)->setSearchParams($searchParams)+ ->setPipelineId($pipeline?->getId() ?? null)->setCountDisabled($disableCount)->setOrderDisabled($orderDisabled)->setUserId($this->user->getId())@@ -83,6 +96,7 @@ class KanbanService* @param string[] $ids* @throws Forbidden* @throws Error+ * @throws NotFound*/public function order(string $entityType, string $group, array $ids): void{@@ -92,11 +106,19 @@ class KanbanServicethrow new ForbiddenSilent("Kanban order is not allowed for portal users.");}+ $isPipeline = $this->pipelineMetadata->isEnabled($entityType);+++ if ($isPipeline) {+ $this->entityProvider->getByClass(PipelineStage::class, $group);+ }+$maxOrderNumber = $this->config->get('kanbanMaxOrderNumber');$this->orderer->setEntityType($entityType)->setGroup($group)+ ->setIsPipeline($isPipeline)->setUserId($this->user->getId())->setMaxNumber($maxOrderNumber)->order($ids);@@ -124,4 +146,49 @@ class KanbanServicethrow new ForbiddenSilent();}}+++ private function getPipelineId(SearchParams $searchParams): ?string+ {+ $pipelineId = null;++ if ($searchParams->getWhere()?->getType() === Type::AND) {+ foreach ($searchParams->getWhere()->getItemList() as $item) {+ if (+ $item->getType() === Type::EQUALS &&+ $item->getAttribute() === Field::PIPELINE . 'Id'+ ) {+ $pipelineId = $item->getValue();++ break;+ }+ }+ }++ if ($pipelineId !== null && !is_string($pipelineId)) {+ return null;+ }++ return $pipelineId;+ }++ /**+ * @throws Forbidden+ * @throws NotFound+ */+ private function getPipeline(string $entityType, SearchParams $searchParams): ?Pipeline+ {+ if (!$this->pipelineMetadata->isEnabled($entityType)) {+ return null;+ }++ $pipeline = null;+ $pipelineId = $this->getPipelineId($searchParams);++ if ($pipelineId) {+ $pipeline = $this->entityProvider->getByClass(Pipeline::class, $pipelineId);+ }++ return $pipeline;+ }}diff --git a/application/Espo/Tools/Kanban/MetadataProvider.php b/application/Espo/Tools/Kanban/MetadataProvider.phpindex 27073d620a..ca55addd62 100644--- a/application/Espo/Tools/Kanban/MetadataProvider.php+++ b/application/Espo/Tools/Kanban/MetadataProvider.php@@ -29,22 +29,40 @@namespace Espo\Tools\Kanban;+use Espo\Core\Exceptions\BadRequest;use Espo\Core\Exceptions\Error;+use Espo\Core\Name\Field;use Espo\Core\Utils\Metadata;+use Espo\Tools\Pipeline\Data\PipelineData;+use Espo\Tools\Pipeline\MetadataProvider as PipelineMetadataProvider;+use Espo\Tools\Pipeline\PipelineDataProvider;class MetadataProvider{public function __construct(private Metadata $metadata,+ private PipelineMetadataProvider $pipelineMetadata,+ private PipelineDataProvider $pipelineDataProvider,) {}-/*** @return string[]* @throws Error+ * @throws BadRequest*/- public function getStatusList(string $entityType): array+ public function getStatusList(string $entityType, ?string $pipelineId = null): array{+ if ($this->pipelineMetadata->isEnabled($entityType)) {+ if (!$pipelineId) {+ throw BadRequest::createWithBody(+ 'noPipeline',+ Error\Body::create()->withMessageTranslation('noPipeline')+ );+ }++ return $this->getPipelineStatusList($entityType, $pipelineId);+ }+$field = $this->getStatusField($entityType);$statusList = $this->metadata->get("entityDefs.$entityType.fields.$field.options");@@ -60,7 +78,10 @@ class MetadataProviderthrow new Error("No options for status field for entity type '$entityType'.");}- return $statusList;+ $statusList = array_diff($statusList, $this->getStatusIgnoreList($entityType));+ $statusList = array_filter($statusList, fn ($it) => $it !== '');++ return array_values($statusList);}/**@@ -68,6 +89,10 @@ class MetadataProvider*/public function getStatusField(string $entityType): string{+ if ($this->pipelineMetadata->isEnabled($entityType)) {+ return Field::PIPELINE_STAGE . 'Id';+ }+$statusField = $this->metadata->get("scopes.$entityType.statusField");if (!$statusField) {@@ -84,4 +109,46 @@ class MetadataProvider{return $this->metadata->get("scopes.$entityType.kanbanStatusIgnoreList") ?? [];}++ private function getPipelineData(string $entityType, string $pipelineId): ?PipelineData+ {+ $pipeline = null;++ $pipelines = $this->pipelineDataProvider->get()[$entityType] ?? [];++ foreach ($pipelines as $it) {+ if ($it->id === $pipelineId) {+ $pipeline = $it;++ break;+ }+ }++ return $pipeline;+ }++ /**+ * @return string[]+ */+ private function getPipelineStatusList(string $entityType, string $pipelineId): array+ {+ $pipeline = $this->getPipelineData($entityType, $pipelineId);++ if (!$pipeline) {+ return [];+ }++ $ignoreStatusList = $this->getStatusIgnoreList($entityType);+ $output = [];++ foreach ($pipeline->stages as $stage) {+ if (in_array($stage->mappedStatus, $ignoreStatusList)) {+ continue;+ }++ $output[] = $stage->id;+ }++ return $output;+ }}diff --git a/application/Espo/Tools/Kanban/OrdererProcessor.php b/application/Espo/Tools/Kanban/OrdererProcessor.phpindex e447976489..d56335760f 100644--- a/application/Espo/Tools/Kanban/OrdererProcessor.php+++ b/application/Espo/Tools/Kanban/OrdererProcessor.php@@ -29,6 +29,7 @@namespace Espo\Tools\Kanban;+use Espo\Core\Exceptions\BadRequest;use Espo\Core\Exceptions\Error;use Espo\Core\Exceptions\ForbiddenSilent;use Espo\Core\Utils\Id\RecordIdGenerator;@@ -46,6 +47,7 @@ class OrdererProcessorprivate ?string $entityType = null;private ?string $group = null;private ?string $userId = null;+ private bool $isPipeline = false;private int $maxNumber = self::DEFAULT_MAX_NUMBER;@@ -56,6 +58,16 @@ class OrdererProcessorprivate MetadataProvider $metadataProvider,) {}+ /**+ * @since 9.4.0+ */+ public function setIsPipeline(bool $isPipeline): self+ {+ $this->isPipeline = $isPipeline;++ return $this;+ }+public function setEntityType(string $entityType): self{$this->entityType = $entityType;@@ -95,6 +107,7 @@ class OrdererProcessor** @throws ForbiddenSilent* @throws Error+ * @throws BadRequest*/public function order(array $ids): void{@@ -203,6 +216,7 @@ class OrdererProcessor/*** @throws Error* @throws ForbiddenSilent+ * @throws BadRequest*/private function validate(): void{@@ -228,6 +242,10 @@ class OrdererProcessorthrow new LogicException("Order is disabled.");}+ if ($this->isPipeline) {+ return;+ }+$statusField = $this->metadataProvider->getStatusField($this->entityType);if (!$statusField) {diff --git a/application/Espo/Tools/LayoutManager/LayoutCustomizer.php b/application/Espo/Tools/LayoutManager/LayoutCustomizer.phpindex 4dd098eb19..8e2ad7c0d9 100644--- a/application/Espo/Tools/LayoutManager/LayoutCustomizer.php+++ b/application/Espo/Tools/LayoutManager/LayoutCustomizer.php@@ -106,11 +106,13 @@ class LayoutCustomizercontinue;}- foreach ($rowItems as &$rowItem) {+ foreach ($rowItems as $rowIndex => &$rowItem) {if (!is_array($rowItem)) {continue;}+ $found = false;+foreach ($rowItem as $i => $cellItem) {if (!$cellItem instanceof stdClass) {continue;@@ -118,8 +120,30 @@ class LayoutCustomizerif (($cellItem->name ?? null) === $field) {$rowItem[$i] = false;++ $found = true;+ }+ }++ if (!$found) {+ continue;+ }++ $notEmptyRow = false;++ foreach ($rowItem as $cellItem) {+ if ($cellItem !== false) {+ $notEmptyRow = true;++ break;}}++ if (!$notEmptyRow) {+ unset($rowItems[$rowIndex]);++ $rowItems = array_values($rowItems);+ }}}diff --git a/application/Espo/Tools/Pipeline/Api/PostMove.php b/application/Espo/Tools/Pipeline/Api/PostMove.phpnew file mode 100644index 0000000000..6628cc5240--- /dev/null+++ b/application/Espo/Tools/Pipeline/Api/PostMove.php@@ -0,0 +1,126 @@+<?php+/************************************************************************+ * This file is part of EspoCRM.+ *+ * EspoCRM – Open Source CRM application.+ * Copyright (C) 2014-2026 EspoCRM, Inc.+ * 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\Pipeline\Api;++use Espo\Core\Acl;+use Espo\Core\Api\Action;+use Espo\Core\Api\Request;+use Espo\Core\Api\Response;+use Espo\Core\Api\ResponseComposer;+use Espo\Core\Exceptions\BadRequest;+use Espo\Core\Exceptions\Forbidden;+use Espo\Core\Exceptions\NotFound;+use Espo\Core\Record\EntityProvider;+use Espo\Core\Select\SearchParams;+use Espo\Core\Utils\Json;+use Espo\Entities\Pipeline;+use Espo\Tools\Pipeline\MoveService;++/**+ * @noinspection PhpUnused+ */+class PostMove implements Action+{+ public function __construct(+ private EntityProvider $entityProvider,+ private Acl $acl,+ private MoveService $moveService,+ ) {}++ public function process(Request $request): Response+ {+ $entity = $this->getEntity($request);+ $type = $this->fetchType($request);+ $searchParams = $this->fetchSearchParams($request);++ $this->moveService->move($entity, $type, $searchParams);++ return ResponseComposer::json(true);+ }++ /**+ * @throws BadRequest+ * @throws Forbidden+ * @throws NotFound+ */+ private function getEntity(Request $request): Pipeline+ {+ $id = $request->getRouteParam('id') ?? throw new BadRequest();++ if (!$this->acl->checkScope(Pipeline::ENTITY_TYPE)) {+ throw new Forbidden();+ }++ $entity = $this->entityProvider->getByClass(Pipeline::class, $id);++ if (!$this->acl->checkEntityEdit($entity)) {+ throw new Forbidden();+ }++ return $entity;+ }++ /**+ * @return MoveService::TYPE_TOP|MoveService::TYPE_UP|MoveService::TYPE_DOWN|MoveService::TYPE_BOTTOM+ * @throws BadRequest+ */+ private function fetchType(Request $request): string+ {+ $type = $request->getRouteParam('type') ?? throw new BadRequest();++ if (+ !in_array($type, [+ MoveService::TYPE_TOP,+ MoveService::TYPE_UP,+ MoveService::TYPE_DOWN,+ MoveService::TYPE_BOTTOM,+ ])+ ) {+ throw new BadRequest("Bad type.");+ }++ return $type;+ }++ private function fetchSearchParams(Request $request): SearchParams+ {+ $body = $request->getParsedBody();++ $searchParams = SearchParams::create();++ if ($body->whereGroup ?? null) {+ $rawWhere = Json::decode(Json::encode($body->whereGroup), true);++ $searchParams = SearchParams::fromRaw(['where' => $rawWhere]);+ }++ return $searchParams;+ }+}diff --git a/application/Espo/Tools/Pipeline/Api/PostStageMove.php b/application/Espo/Tools/Pipeline/Api/PostStageMove.phpnew file mode 100644index 0000000000..bd4f661937--- /dev/null+++ b/application/Espo/Tools/Pipeline/Api/PostStageMove.php@@ -0,0 +1,111 @@+<?php+/************************************************************************+ * This file is part of EspoCRM.+ *+ * EspoCRM – Open Source CRM application.+ * Copyright (C) 2014-2026 EspoCRM, Inc.+ * 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\Pipeline\Api;++use Espo\Core\Acl;+use Espo\Core\Api\Action;+use Espo\Core\Api\Request;+use Espo\Core\Api\Response;+use Espo\Core\Api\ResponseComposer;+use Espo\Core\Exceptions\BadRequest;+use Espo\Core\Exceptions\Forbidden;+use Espo\Core\Exceptions\NotFound;+use Espo\Core\Record\EntityProvider;+use Espo\Entities\PipelineStage;+use Espo\Tools\Pipeline\MoveService;+use Espo\Tools\Pipeline\StageMoveService;++/**+ * @noinspection PhpUnused+ */+class PostStageMove implements Action+{+ public function __construct(+ private EntityProvider $entityProvider,+ private Acl $acl,+ private StageMoveService $moveService,+ ) {}++ public function process(Request $request): Response+ {+ $entity = $this->getEntity($request);+ $type = $this->fetchType($request);++ if ($type === MoveService::TYPE_UP) {+ $this->moveService->moveUp($entity);+ } else {+ $this->moveService->moveDown($entity);+ }++ return ResponseComposer::json(true);+ }++ /**+ * @throws BadRequest+ * @throws Forbidden+ * @throws NotFound+ */+ private function getEntity(Request $request): PipelineStage+ {+ $id = $request->getRouteParam('id') ?? throw new BadRequest();++ if (!$this->acl->checkScope(PipelineStage::ENTITY_TYPE)) {+ throw new Forbidden();+ }++ $entity = $this->entityProvider->getByClass(PipelineStage::class, $id);++ if (!$this->acl->checkEntityEdit($entity)) {+ throw new Forbidden();+ }++ return $entity;+ }++ /**+ * @return MoveService::TYPE_UP|MoveService::TYPE_DOWN+ * @throws BadRequest+ */+ private function fetchType(Request $request): string+ {+ $type = $request->getRouteParam('type') ?? throw new BadRequest();++ if (+ !in_array($type, [+ MoveService::TYPE_UP,+ MoveService::TYPE_DOWN,+ ])+ ) {+ throw new BadRequest("Not supported type.");+ }++ return $type;+ }+}diff --git a/application/Espo/Tools/Pipeline/CacheClearer.php b/application/Espo/Tools/Pipeline/CacheClearer.phpnew file mode 100644index 0000000000..0e877c70a5--- /dev/null+++ b/application/Espo/Tools/Pipeline/CacheClearer.php@@ -0,0 +1,49 @@+<?php+/************************************************************************+ * This file is part of EspoCRM.+ *+ * EspoCRM – Open Source CRM application.+ * Copyright (C) 2014-2026 EspoCRM, Inc.+ * 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\Pipeline;++use Espo\Core\Utils\DataCache;+use Espo\Core\WebSocket\Submission;++class CacheClearer+{+ private const string CACHE_KEY = 'pipelines';++ public function __construct(+ private DataCache $dataCache,+ private Submission $submission,+ ) {}++ public function clear(): void+ {+ $this->dataCache->clear(self::CACHE_KEY);+ $this->submission->submit('appParamsUpdate');+ }+}diff --git a/application/Espo/Tools/Pipeline/Data/PipelineData.php b/application/Espo/Tools/Pipeline/Data/PipelineData.phpnew file mode 100644index 0000000000..2cc71cee48--- /dev/null+++ b/application/Espo/Tools/Pipeline/Data/PipelineData.php@@ -0,0 +1,48 @@+<?php+/************************************************************************+ * This file is part of EspoCRM.+ *+ * EspoCRM – Open Source CRM application.+ * Copyright (C) 2014-2026 EspoCRM, Inc.+ * 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\Pipeline\Data;++readonly class PipelineData+{+ /**+ * @param string $entityType+ * @param StageData[] $stages+ * @param string[] $teamIds+ */+ public function __construct(+ public string $id,+ public string $name,+ public string $entityType,+ public array $stages,+ public bool $isAvailableForAll,+ public array $teamIds,+ public ?int $color,+ ) {}+}diff --git a/application/Espo/Tools/Pipeline/Data/StageData.php b/application/Espo/Tools/Pipeline/Data/StageData.phpnew file mode 100644index 0000000000..2004370a61--- /dev/null+++ b/application/Espo/Tools/Pipeline/Data/StageData.php@@ -0,0 +1,40 @@+<?php+/************************************************************************+ * This file is part of EspoCRM.+ *+ * EspoCRM – Open Source CRM application.+ * Copyright (C) 2014-2026 EspoCRM, Inc.+ * 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\Pipeline\Data;++readonly class StageData+{+ public function __construct(+ public string $id,+ public string $name,+ public string $mappedStatus,+ public ?string $style,+ ) {}+}diff --git a/application/Espo/Tools/Pipeline/MetadataProvider.php b/application/Espo/Tools/Pipeline/MetadataProvider.phpnew file mode 100644index 0000000000..5eaeeb3606--- /dev/null+++ b/application/Espo/Tools/Pipeline/MetadataProvider.php@@ -0,0 +1,49 @@+<?php+/************************************************************************+ * This file is part of EspoCRM.+ *+ * EspoCRM – Open Source CRM application.+ * Copyright (C) 2014-2026 EspoCRM, Inc.+ * 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\Pipeline;++use Espo\Core\Utils\Metadata;++class MetadataProvider+{+ public function __construct(+ private Metadata $metadata,+ ) {}++ public function isEnabled(string $entityType): bool+ {+ return $this->metadata->get("scopes.$entityType.pipelines") === true;+ }++ public function getStatusField(string $entityType): ?string+ {+ return $this->metadata->get("scopes.$entityType.statusField");+ }+}diff --git a/application/Espo/Tools/Pipeline/MoveService.php b/application/Espo/Tools/Pipeline/MoveService.phpnew file mode 100644index 0000000000..f078bcc40e--- /dev/null+++ b/application/Espo/Tools/Pipeline/MoveService.php@@ -0,0 +1,259 @@+<?php+/************************************************************************+ * This file is part of EspoCRM.+ *+ * EspoCRM – Open Source CRM application.+ * Copyright (C) 2014-2026 EspoCRM, Inc.+ * 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\Pipeline;++use Espo\Core\Exceptions\BadRequest;+use Espo\Core\Exceptions\Forbidden;+use Espo\Core\ORM\Repository\Option\SaveOption;+use Espo\Core\Select\SearchParams;+use Espo\Core\Select\SelectBuilderFactory;+use Espo\Entities\Pipeline;+use Espo\Entities\PipelineStage;+use Espo\ORM\EntityManager;+use Espo\ORM\Name\Attribute;+use Espo\ORM\Query\Part\Order;+use Espo\ORM\Query\SelectBuilder;++class MoveService+{+ public const string TYPE_TOP = 'top';+ public const string TYPE_BOTTOM = 'bottom';+ public const string TYPE_UP = 'up';+ public const string TYPE_DOWN = 'down';++ public function __construct(+ private EntityManager $entityManager,+ private SelectBuilderFactory $selectBuilderFactory,+ private CacheClearer $cacheClearer,+ ) {}++ /**+ * @param self::TYPE_TOP|self::TYPE_BOTTOM|self::TYPE_UP|self::TYPE_DOWN $type+ * @throws BadRequest+ * @throws Forbidden+ */+ public function move(+ Pipeline $entity,+ string $type,+ SearchParams $searchParams,+ ): void {++ $builder = $this->createSelectBuilder($searchParams, $entity);++ if ($type === self::TYPE_TOP) {+ $this->moveToTop($entity, $builder);+ } else if ($type === self::TYPE_BOTTOM) {+ $this->moveToBottom($entity, $builder);+ } else if ($type === self::TYPE_UP) {+ $this->moveUp($entity, $builder);+ } else {+ $this->moveDown($entity, $builder);+ }++ $this->reOrder($entity::class);++ $this->cacheClearer->clear();+ }++ /**+ * @param class-string<Pipeline|PipelineStage> $className+ */+ public function reOrder(string $className, ?string $parentId = null): void+ {+ $this->entityManager+ ->getTransactionManager()+ ->run(fn () => $this->reOrderInternal($className, $parentId));+ }++ /**+ * @param class-string<Pipeline|PipelineStage> $className+ */+ private function reOrderInternal(string $className, ?string $parentId = null): void+ {+ $this->entityManager+ ->getRDBRepositoryByClass($className)+ ->select(Attribute::ID)+ ->forUpdate()+ ->sth()+ ->find();++ $builder = $this->entityManager+ ->getRDBRepositoryByClass($className)+ ->sth()+ ->order(Pipeline::FIELD_ORDER);++ if ($className === PipelineStage::class) {+ $builder->where([+ PipelineStage::ATTR_PIPELINE_ID => $parentId,+ ]);+ }++ $collection = $builder->find();++ foreach ($collection as $i => $entity) {+ $order = $i + 1;++ if ($entity->getOrder() === $order) {+ continue;+ }++ $entity->set(Pipeline::FIELD_ORDER, $order);++ $this->entityManager->saveEntity($entity, [SaveOption::SKIP_HOOKS => true]);+ }+ }++ /**+ * @throws BadRequest+ * @throws Forbidden+ */+ private function createSelectBuilder(+ SearchParams $searchParams,+ Pipeline $entity,+ ): SelectBuilder {++ /** @noinspection PhpRedundantOptionalArgumentInspection */+ return $this->selectBuilderFactory+ ->create()+ ->from($entity::ENTITY_TYPE)+ ->withSearchParams($searchParams)+ ->withStrictAccessControl()+ ->buildQueryBuilder()+ ->limit(null, null)+ ->order([]);+ }++ private function moveUp(+ Pipeline $entity,+ SelectBuilder $builder,+ ): void {++ $query = $builder+ ->where([Pipeline::FIELD_ORDER . '<' => $entity->getOrder()])+ ->order(Pipeline::FIELD_ORDER, Order::DESC)+ ->build();++ $another = $this->entityManager+ ->getRDBRepositoryByClass($entity::class)+ ->clone($query)+ ->findOne();++ if (!$another) {+ return;+ }++ $index = $entity->getOrder();++ $entity->set(Pipeline::FIELD_ORDER, $another->getOrder());+ $another->set(Pipeline::FIELD_ORDER, $index);++ $this->entityManager->saveEntity($entity);+ $this->entityManager->saveEntity($another);+ }++ private function moveDown(+ Pipeline $entity,+ SelectBuilder $builder,+ ): void {++ $query = $builder+ ->where([Pipeline::FIELD_ORDER . '>' => $entity->getOrder()])+ ->order(Pipeline::FIELD_ORDER, Order::ASC)+ ->build();++ $another = $this->entityManager+ ->getRDBRepositoryByClass($entity::class)+ ->clone($query)+ ->findOne();++ if (!$another) {+ return;+ }++ $index = $entity->getOrder();++ $entity->set(Pipeline::FIELD_ORDER, $another->getOrder());+ $another->set(Pipeline::FIELD_ORDER, $index);++ $this->entityManager->saveEntity($entity);+ $this->entityManager->saveEntity($another);++ $this->entityManager->refreshEntity($entity);+ $this->entityManager->refreshEntity($another);+ }++ private function moveToTop(+ Pipeline $entity,+ SelectBuilder $builder,+ ): void {++ $query = $builder+ ->where([Pipeline::FIELD_ORDER . '<' => $entity->getOrder()])+ ->order(Pipeline::FIELD_ORDER, Order::ASC)+ ->build();++ $another = $this->entityManager+ ->getRDBRepositoryByClass($entity::class)+ ->clone($query)+ ->findOne();++ if (!$another) {+ return;+ }++ $entity->set(Pipeline::FIELD_ORDER, $another->getOrder() - 1);++ $this->entityManager->saveEntity($entity);+ }++ private function moveToBottom(+ Pipeline $entity,+ SelectBuilder $builder,+ ): void {++ $query = $builder+ ->where([Pipeline::FIELD_ORDER . '>' => $entity->getOrder()])+ ->order(Pipeline::FIELD_ORDER, Order::DESC)+ ->build();++ $another = $this->entityManager+ ->getRDBRepositoryByClass($entity::class)+ ->clone($query)+ ->findOne();++ if (!$another) {+ return;+ }++ $entity->set(Pipeline::FIELD_ORDER, $another->getOrder() + 1);++ $this->entityManager->saveEntity($entity);+ }+}diff --git a/application/Espo/Tools/Pipeline/PipelineDataProvider.php b/application/Espo/Tools/Pipeline/PipelineDataProvider.phpnew file mode 100644index 0000000000..2016a016cc--- /dev/null+++ b/application/Espo/Tools/Pipeline/PipelineDataProvider.php@@ -0,0 +1,324 @@+<?php+/************************************************************************+ * This file is part of EspoCRM.+ *+ * EspoCRM – Open Source CRM application.+ * Copyright (C) 2014-2026 EspoCRM, Inc.+ * 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\Pipeline;++use Espo\Core\Utils\Config\SystemConfig;+use Espo\Core\Utils\DataCache;+use Espo\Core\Utils\Log;+use Espo\Core\Utils\Metadata;+use Espo\Entities\Pipeline;+use Espo\Entities\PipelineStage;+use Espo\ORM\EntityManager;+use Espo\Tools\Pipeline\Data\PipelineData;+use Espo\Tools\Pipeline\Data\StageData;+use stdClass;+use Throwable;++class PipelineDataProvider+{+ private const int LIMIT = 100;+ private const string CACHE_KEY = 'pipelines';++ public function __construct(+ private Metadata $metadata,+ private EntityManager $entityManager,+ private SystemConfig $systemConfig,+ private DataCache $dataCache,+ private Log $log,+ ) {}++ /**+ * @return array<string, PipelineData[]>+ */+ public function get(): array+ {+ $data = null;+ $store = false;++ if ($this->systemConfig->useCache()) {+ $data = $this->getFromCache();++ if (!$data) {+ $store = true;+ }+ }++ $data ??= $this->build();++ if ($store) {+ $this->storeCache($data);+ }++ return $data;+ }++ /**+ * @return ?array<string, PipelineData[]>+ */+ private function getFromCache(): ?array+ {+ if (!$this->dataCache->has(self::CACHE_KEY)) {+ return null;+ }++ try {+ return $this->tryGetFromCache();+ } catch (Throwable $e) {+ $this->log->warning("Pipeline cache read error.", [+ 'exception' => $e,+ ]);++ return null;+ }+ }++ /**+ * @return array<string, PipelineData[]>+ */+ private function build(): array+ {+ $output = [];++ foreach ($this->getEntityTypeList() as $entityType) {+ $output[$entityType] = $this->buildForEntityType($entityType);+ }++ return $output;+ }++ /**+ * @return string[]+ */+ private function getEntityTypeList(): array+ {+ $entityTypeList = [];++ /** @var array<string, array<string, mixed>> $scopes */+ $scopes = $this->metadata->get('scopes') ?? [];++ foreach ($scopes as $scope => $defs) {+ if (+ !($defs['entity'] ?? false) ||+ !($defs['pipelines'] ?? false) ||+ ($defs['disabled'] ?? false)+ ) {+ continue;+ }++ $entityTypeList[] = $scope;+ }++ return $entityTypeList;+ }++ /**+ * @return PipelineData[]+ */+ private function buildForEntityType(string $entityType): array+ {+ $pipelines = $this->entityManager+ ->getRDBRepositoryByClass(Pipeline::class)+ ->where([+ Pipeline::FIELD_STATUS => Pipeline::STATUS_ACTIVE,+ Pipeline::FIELD_ENTITY_TYPE=> $entityType,+ ])+ ->order(Pipeline::FIELD_ORDER)+ ->limit(0, self::LIMIT)+ ->find();++ $output = [];++ foreach ($pipelines as $pipeline) {+ $output[] = new PipelineData(+ id: $pipeline->getId(),+ name: $pipeline->getName(),+ entityType: $entityType,+ stages: $this->getStages($pipeline),+ isAvailableForAll: $pipeline->isAvailableForAll(),+ teamIds: $pipeline->getTeams()->getIdList(),+ color: $pipeline->getColor(),+ );+ }++ return $output;+ }++ /**+ * @return StageData[]+ */+ private function getStages(Pipeline $pipeline): array+ {+ $stages = $this->entityManager+ ->getRDBRepositoryByClass(PipelineStage::class)+ ->where([+ PipelineStage::ATTR_PIPELINE_ID => $pipeline->getId(),+ ])+ ->order(PipelineStage::FIELD_ORDER)+ ->limit(0, self::LIMIT)+ ->find();++ $output = [];++ foreach ($stages as $stage) {+ $output[] = new StageData(+ id: $stage->getId(),+ name: $stage->getName(),+ mappedStatus: $stage->getMappedStatus(),+ style: $this->getStageStyle($pipeline, $stage),+ );+ }++ return $output;+ }++ /**+ * @param array<string, PipelineData[]> $data+ */+ private function storeCache(array $data): void+ {+ $output = (object) [];++ foreach ($data as $entityType => $pipelines) {+ $subOutput = [];++ foreach ($pipelines as $pipeline) {+ $subOutput[] = (object) [+ 'id' => $pipeline->id,+ 'name' => $pipeline->name,+ 'entityType' => $entityType,+ 'stages' => $this->serializeStages($pipeline->stages),+ 'isAvailableForAll' => $pipeline->isAvailableForAll,+ 'teamIds' => $pipeline->teamIds,+ ];+ }++ $output->$entityType = $subOutput;+ }++ $this->dataCache->store(self::CACHE_KEY, $output);+ }++ /**+ * @param array<string, mixed> $data+ */+ private function unserializePipelineData(array $data): PipelineData+ {+ $data['stages'] = $this->unserializeStages($data['stages'] ?? []);++ return new PipelineData(...$data);+ }++ /**+ * @param array<int, mixed> $stages+ * @return StageData[]+ */+ private function unserializeStages(array $stages): array+ {+ $output = [];++ foreach ($stages as $item) {+ if (!$item instanceof stdClass) {+ continue;+ }++ $output[] = new StageData(...get_object_vars($item));+ }++ return $output;+ }++ /**+ * @param StageData[] $stages+ * @return stdClass[]+ */+ private function serializeStages(array $stages): array+ {+ $output = [];++ foreach ($stages as $stage) {+ $output[] = (object) [+ 'id' => $stage->id,+ 'name' => $stage->name,+ 'mappedStatus' => $stage->mappedStatus,+ ];+ }++ return $output;+ }++ /**+ * @return ?array<string, PipelineData[]>+ */+ private function tryGetFromCache(): ?array+ {+ $data = $this->dataCache->get(self::CACHE_KEY);++ if (!$data instanceof stdClass) {+ $this->log->warning("Bad pipeline cache.");++ return null;+ }++ $output = [];++ foreach (get_object_vars($data) as $entityType => $list) {+ if (!is_array($list)) {+ $this->log->warning("Bad pipeline cache, non-array.");++ return null;+ }++ $subOutput = [];++ foreach ($list as $item) {+ if (!$item instanceof stdClass) {+ $this->log->warning("Bad pipeline item cache.");++ return null;+ }++ $subOutput[] = $this->unserializePipelineData(get_object_vars($item));+ }++ $output[$entityType] = $subOutput;+ }++ return $output;+ }++ private function getStageStyle(Pipeline $pipeline, PipelineStage $stage): ?string+ {+ $entityType = $pipeline->getTargetEntityType();+ $field = $pipeline->getTargetField();+ $status = $stage->getMappedStatus();++ return $this->metadata->get("entityDefs.$entityType.fields.$field.style.$status");+ }+}diff --git a/application/Espo/Tools/Pipeline/PipelineDataUserFilter.php b/application/Espo/Tools/Pipeline/PipelineDataUserFilter.phpnew file mode 100644index 0000000000..247d5418ac--- /dev/null+++ b/application/Espo/Tools/Pipeline/PipelineDataUserFilter.php@@ -0,0 +1,79 @@+<?php+/************************************************************************+ * This file is part of EspoCRM.+ *+ * EspoCRM – Open Source CRM application.+ * Copyright (C) 2014-2026 EspoCRM, Inc.+ * 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\Pipeline;++use Espo\Core\Acl;+use Espo\Entities\User;+use Espo\Tools\Pipeline\Data\PipelineData;++class PipelineDataUserFilter+{+ public function __construct(+ private Acl $acl,+ private User $user,+ ) {}++ /**+ * @param array<string, PipelineData[]> $data+ * @return array<string, PipelineData[]>+ */+ public function filter(array $data): array+ {+ if ($this->user->isAdmin()) {+ return $data;+ }++ foreach ($data as $entityType => $pipelines) {+ if (!$this->acl->checkScope($entityType)) {+ unset($data[$entityType]);++ continue;+ }++ $filtered = array_filter($pipelines, function ($pipelineData) {+ if ($pipelineData->isAvailableForAll) {+ return true;+ }++ if ($this->user->isPortal()) {+ return false;+ }++ return array_intersect($pipelineData->teamIds, $this->user->getTeamIdList()) !== [];+ });++ $filtered = array_values($filtered);++ $data[$entityType] = $filtered;+ }++ return $data;+ }+}diff --git a/application/Espo/Tools/Pipeline/StageMoveService.php b/application/Espo/Tools/Pipeline/StageMoveService.phpnew file mode 100644index 0000000000..bedb483b3e--- /dev/null+++ b/application/Espo/Tools/Pipeline/StageMoveService.php@@ -0,0 +1,132 @@+<?php+/************************************************************************+ * This file is part of EspoCRM.+ *+ * EspoCRM – Open Source CRM application.+ * Copyright (C) 2014-2026 EspoCRM, Inc.+ * 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\Pipeline;++use Espo\Core\Exceptions\Conflict;+use Espo\Entities\PipelineStage;+use Espo\ORM\EntityManager;+use RuntimeException;++class StageMoveService+{+ public function __construct(+ private EntityManager $entityManager,+ private CacheClearer $cacheClearer,+ ) {}++ /**+ * @throws Conflict+ */+ public function moveUp(PipelineStage $stage): void+ {+ $columns = $this->getStages($stage);+ $index = $this->getIndex($columns, $stage);++ $anotherColumn = $columns[$index - 1] ?? null;++ if (!$anotherColumn) {+ throw new Conflict("Can't move first.");+ }++ $this->swapStages($anotherColumn, $stage);++ $this->cacheClearer->clear();+ }++ /**+ * @throws Conflict+ */+ public function moveDown(PipelineStage $column): void+ {+ $columns = $this->getStages($column);+ $index = $this->getIndex($columns, $column);++ $anotherColumn = $columns[$index + 1] ?? null;++ if (!$anotherColumn) {+ throw new Conflict("Can't move last.");+ }++ $this->swapStages($anotherColumn, $column);+ }++ /**+ * @throws Conflict+ */+ private function swapStages(PipelineStage $anotherColumn, PipelineStage $column): void+ {+ if ($anotherColumn->getMappedStatus() !== $column->getMappedStatus()) {+ throw new Conflict("Can't break status order.");+ }++ $order = $column->getOrder();+ $column->setOrder($anotherColumn->getOrder());+ $anotherColumn->setOrder($order);++ $this->entityManager->saveEntity($column);+ $this->entityManager->saveEntity($anotherColumn);+ }++ /**+ * @return PipelineStage[]+ */+ private function getStages(PipelineStage $stage): array+ {+ $collection = $this->entityManager+ ->getRDBRepositoryByClass(PipelineStage::class)+ ->where([PipelineStage::ATTR_PIPELINE_ID => $stage->getPipeline()->getId()])+ ->order(PipelineStage::FIELD_ORDER)+ ->find();++ return iterator_to_array($collection);+ }++ /**+ * @param PipelineStage[] $columns+ */+ private function getIndex(array $columns, PipelineStage $column): int+ {+ $index = -1;++ foreach ($columns as $i => $it) {+ if ($it->getId() === $column->getId()) {+ $index = $i;++ break;+ }+ }++ if ($index < 0) {+ throw new RuntimeException("Stage not found.");+ }++ return $index;+ }+}diff --git a/client/res/templates/record/kanban.tpl b/client/res/templates/record/kanban.tplindex 814bed0fab..e9a943d4a1 100644--- a/client/res/templates/record/kanban.tpl+++ b/client/res/templates/record/kanban.tpl@@ -1,6 +1,10 @@{{#if topBar}}<div class="list-buttons-container clearfix">+ {{#if usePipeline}}+ <div class="btn-group">{{{pipelineDropdown}}}</div>+ {{/if}}+{{#if displayTotalCount}}<div class="text-muted total-count"><spandiff --git a/client/src/controllers/admin.js b/client/src/controllers/admin.jsindex db0d374b31..96e10fa622 100644--- a/client/src/controllers/admin.js+++ b/client/src/controllers/admin.js@@ -32,6 +32,7 @@ import AdminIndexView from 'views/admin/index';import {inject} from 'di';import Language from 'language';import EditView from 'views/edit';+import AdminPipelinesListForEntityType from 'views/admin/pipelines/list-for-entity-type';class AdminController extends Controller {@@ -384,6 +385,37 @@ class AdminController extends Controller {});}+ // noinspection JSUnusedGlobalSymbols+ /**+ *+ * @param {Record} options+ */+ async actionPipelines(options = {}) {+ if (options?.scope) {+ const collection = await this.collectionFactory.create('Pipeline');++ collection.maxSize = this.getConfig().get('recordsPerPage');++ collection.where = [{+ type: 'equals',+ attribute: 'entityType',+ value: options.scope,+ }];++ const view = new AdminPipelinesListForEntityType({+ scope: 'Pipeline',+ collection,+ targetEntityType: options.scope,+ });++ this.main(view);++ return;+ }++ this.main('views/admin/pipelines/main');+ }+// noinspection JSUnusedGlobalSymbolsactionAuthLog() {this.collectionFactory.create('AuthLogRecord', collection => {diff --git a/client/src/handlers/pipeline-stage/move-row-action.js b/client/src/handlers/pipeline-stage/move-row-action.jsnew file mode 100644index 0000000000..fcdc767f40--- /dev/null+++ b/client/src/handlers/pipeline-stage/move-row-action.js@@ -0,0 +1,92 @@+/************************************************************************+ * This file is part of EspoCRM.+ *+ * EspoCRM – Open Source CRM application.+ * Copyright (C) 2014-2026 EspoCRM, Inc.+ * 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.+ ************************************************************************/++import RowActionHandler from 'handlers/row-action';++export default class PipelineStageMoveRowActionHandler extends RowActionHandler+{+ isAvailable(model, action) {+ const collection = model.collection;++ if (!collection) {+ return false;+ }++ if (action === 'moveUp') {+ if (collection.indexOf(model) <= 0) {+ return false;+ }++ const index = collection.models.findIndex(m => m === model);++ const prevModel = this.collection.at(index - 1);++ if (!prevModel || prevModel.attributes.mappedStatus !== model.attributes.mappedStatus) {+ return false;+ }+ }++ if (action === 'moveDown') {+ if (collection.indexOf(model) >= collection.total - 1) {+ return false;+ }++ const index = collection.models.findIndex(m => m === model);++ const nextModel = this.collection.at(index + 1);++ if (!nextModel || nextModel.attributes.mappedStatus !== model.attributes.mappedStatus) {+ return false;+ }+ }++ return collection.orderBy === 'order' && collection.order === 'asc';+ }++ async process(model, action) {+ let type;++ if (action === 'moveUp') {+ type = 'up';+ } else if (action === 'moveDown') {+ type = 'down';+ } else {+ throw new Error();+ }++ Espo.Ui.notifyWait();++ await Espo.Ajax.postRequest(`${model.entityType}/${model.id}/move/${type}`, {+ whereGroup: this.collection.getWhere(),+ });++ await this.collection.fetch();++ Espo.Ui.notify();+ }+}diff --git a/client/src/handlers/pipeline/move-row-action.js b/client/src/handlers/pipeline/move-row-action.jsnew file mode 100644index 0000000000..a016b899d7--- /dev/null+++ b/client/src/handlers/pipeline/move-row-action.js@@ -0,0 +1,80 @@+/************************************************************************+ * This file is part of EspoCRM.+ *+ * EspoCRM – Open Source CRM application.+ * Copyright (C) 2014-2026 EspoCRM, Inc.+ * 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.+ ************************************************************************/++import RowActionHandler from 'handlers/row-action';++export default class PipelineMoveRowActionHandler extends RowActionHandler {++ isAvailable(model, action) {+ const collection = model.collection;++ if (!collection) {+ return false;+ }++ if (action === 'moveToTop' || action === 'moveUp') {+ if (collection.indexOf(model) <= 0) {+ return false;+ }+ }++ if (action === 'moveToBottom' || action === 'moveDown') {+ if (collection.indexOf(model) >= collection.total - 1) {+ return false;+ }+ }++ return collection.orderBy === 'order' && collection.order === 'asc';+ }++ async process(model, action) {+ let type;++ if (action === 'moveToTop') {+ type = 'top';+ } else if (action === 'moveToBottom') {+ type = 'bottom';+ } else if (action === 'moveUp') {+ type = 'up';+ } else if (action === 'moveDown') {+ type = 'down';+ } else {+ throw new Error();+ }++ Espo.Ui.notifyWait();++ await Espo.Ajax.postRequest(`${model.entityType}/${model.id}/move/${type}`, {+ whereGroup: this.collection.getWhere(),+ });++ await this.collection.fetch();++ Espo.Ui.notify();+ }+}diff --git a/client/src/handlers/record/pipeline-view-setup.js b/client/src/handlers/record/pipeline-view-setup.jsnew file mode 100644index 0000000000..67d3ba09e6--- /dev/null+++ b/client/src/handlers/record/pipeline-view-setup.js@@ -0,0 +1,145 @@+/************************************************************************+ * This file is part of EspoCRM.+ *+ * EspoCRM – Open Source CRM application.+ * Copyright (C) 2014-2026 EspoCRM, Inc.+ * 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.+ ************************************************************************/+import {inject} from 'di';+import Metadata from 'metadata';+import AppParams from 'app-params';+import PipelinesHelper from 'helpers/misc/pipelines';++// noinspection JSUnusedGlobalSymbols+export default class PipelineViewSetupHandler {++ /**+ * @private+ * @type {Metadata}+ */+ @inject(Metadata)+ metadata++ /**+ * @private+ * @type {import('model').default}+ */+ model++ /**+ * @private+ * @type {import('views/record/detail').default}+ */+ view++ /**+ * @private+ * @type {AppParams}+ */+ @inject(AppParams)+ appParams++ /**+ * @private+ * @type {{id: string, stages: {id: string, name: string, style: string|null}[]}[]}+ */+ pipelines++ /**+ * @param {import('views/record/detail').default} view+ */+ constructor(view) {+ this.view = view;+ this.model = view.model;+ }++ process() {+ const entityType = this.model.entityType;++ if (this.metadata.get(`scopes.${entityType}.pipelines`) !== true) {+ return;+ }++ this.pipelines = new PipelinesHelper().get(entityType);++ this.model.onChange({+ owner: this.view,+ attributes: ['pipelineId'],+ callback: o => {+ if (!o.ui) {+ return;+ }++ setTimeout(() => this.updateStage(), 1);+ },+ });+ }++ /**+ * @private+ */+ updateStage() {+ const pipelineId = this.model.attributes.pipelineId;++ if (!pipelineId) {+ this.setStageNull();++ return;+ }++ const pipeline = this.pipelines.find(it => it.id === pipelineId);++ if (!pipeline) {+ this.setStageNull();++ return;+ }++ const stage = pipeline.stages[0];++ if (!stage) {+ this.setStageNull();++ return;+ }++ this.model.setMultiple({+ pipelineStageId: stage.id,+ pipelineStageName: stage.name,+ });++ this.model.trigger('pipeline-changed');+ }++ /**+ * @private+ */+ setStageNull() {+ this.model.setMultiple({+ pipelineStageId: null,+ pipelineStageName: null,+ });++ this.model.trigger('pipeline-changed');+ }+}diff --git a/client/src/helpers/field/options-provider.js b/client/src/helpers/field/options-provider.jsnew file mode 100644index 0000000000..6990ae215c--- /dev/null+++ b/client/src/helpers/field/options-provider.js@@ -0,0 +1,106 @@+/************************************************************************+ * This file is part of EspoCRM.+ *+ * EspoCRM – Open Source CRM application.+ * Copyright (C) 2014-2026 EspoCRM, Inc.+ * 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.+ ************************************************************************/++import {inject} from 'di';+import Metadata from 'metadata';+import Language from 'language';++/**+ * @since 9.4.0+ */+export default class OptionsProvider {++ /**+ * @private+ * @type {Metadata}+ */+ @inject(Metadata)+ metadata++ /**+ * @private+ * @type {Language}+ */+ @inject(Language)+ language++ /**+ * @param {string} entityType+ * @param {string} field+ * @return {{+ * name: string,+ * label: string,+ * style: string|null,+ * }[]}+ */+ get(entityType, field) {+ /**+ * @type {{+ * options?: string[],+ * style?: Record<string, string>,+ * optionsReference?: string|null,+ * optionsPath?: string|null+ * }} */+ const params = this.metadata.get(`entityDefs.${entityType}.fields.${field}`);++ if (!params) {+ return [];+ }++ let sourceEntityType = entityType;+ let sourceField = field;+ let styleMap = params.style ?? {};++ let optionsPath = params.optionsPath;++ if (!optionsPath && params.optionsReference) {+ const [refEntityType, refField] = params.optionsReference.split('.');++ optionsPath = `entityDefs.${refEntityType}.fields.${refField}.options`;++ sourceEntityType = refEntityType;+ sourceField = refField;++ styleMap = this.metadata.get(`entityDefs.${refEntityType}.fields.${refField}.style`) ?? {};+ }++ let options = params.options;++ if (optionsPath) {+ options = this.metadata.get(optionsPath);+ }++ return options.map(it => {+ return {+ name: it,+ label: this.language.translateOption(it, sourceField, sourceEntityType),+ style: styleMap[it] ?? null,+ }+ });+ }+}diff --git a/client/src/helpers/misc/pipelines.js b/client/src/helpers/misc/pipelines.jsnew file mode 100644index 0000000000..c77662ba8d--- /dev/null+++ b/client/src/helpers/misc/pipelines.js@@ -0,0 +1,76 @@+/************************************************************************+ * This file is part of EspoCRM.+ *+ * EspoCRM – Open Source CRM application.+ * Copyright (C) 2014-2026 EspoCRM, Inc.+ * 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.+ ************************************************************************/++import {inject} from 'di';+import AppParams from 'app-params';+import Metadata from 'metadata';++/**+ * @since 9.4.0+ */+export default class PipelinesHelper {++ /**+ * @private+ * @type {AppParams}+ */+ @inject(AppParams)+ appParams++ /**+ * @private+ * @type {Metadata}+ */+ @inject(Metadata)+ metadata++ /**+ * @param {string} entityType+ * @return {{+ * id: string,+ * name: string,+ * stages: {+ * id: string,+ * name: string,+ * style: string|null,+ * }[],+ * color: number|null,+ * }[]}+ */+ get(entityType) {+ return (this.appParams.get('pipelines') ?? {})[entityType] ?? [];+ }++ /**+ * @param {string} entityType+ * @return {boolean}+ */+ isEnabled(entityType) {+ return this.metadata.get(`scopes.${entityType}.pipelines`) === true;+ }+}diff --git a/client/src/helpers/model/defaults-populator.js b/client/src/helpers/model/defaults-populator.jsindex 9ab1708f3b..69e392bf54 100644--- a/client/src/helpers/model/defaults-populator.js+++ b/client/src/helpers/model/defaults-populator.js@@ -33,6 +33,7 @@ import Settings from 'models/settings';import User from 'models/user';import AclManager from 'acl-manager';import Preferences from 'models/preferences';+import PipelinesHelper from 'helpers/misc/pipelines';/*** Defaults populator.@@ -179,6 +180,18 @@ class DefaultsPopulator {defaultHash.collaboratorsIds = [this.user.id];defaultHash.collaboratorsNames = {[this.user.id]: this.user.attributes.name};}++ if (this.metadata.get(`scopes.${model.entityType}.pipelines`)) {+ const firstPipeline = new PipelinesHelper().get(model.entityType)[0] ?? null;++ if (firstPipeline) {+ defaultHash.pipelineId = firstPipeline.id;+ defaultHash.pipelineName = firstPipeline.name;++ defaultHash.pipelineStageId = firstPipeline.stages[0]?.id ?? null;+ defaultHash.pipelineStageName = firstPipeline.stages[0]?.name ?? null;+ }+ }}/**diff --git a/client/src/views/admin/pipelines/list-for-entity-type.js b/client/src/views/admin/pipelines/list-for-entity-type.jsnew file mode 100644index 0000000000..b86db0351e--- /dev/null+++ b/client/src/views/admin/pipelines/list-for-entity-type.js@@ -0,0 +1,88 @@+/************************************************************************+ * This file is part of EspoCRM.+ *+ * EspoCRM – Open Source CRM application.+ * Copyright (C) 2014-2026 EspoCRM, Inc.+ * 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.+ ************************************************************************/++import ListView from 'views/list';++export default class AdminPipelinesListForEntityType extends ListView {++ searchPanel = false+ keepCurrentRootUrl = true++ /**+ * @private+ * @type {string}+ */+ targetEntityType++ setup() {+ super.setup();++ this.targetEntityType = this.options.targetEntityType;+ }++ getCreateAttributes() {+ return {+ entityType: this.targetEntityType,+ field: this.getMetadata().get(`scopes.${this.targetEntityType}.statusField`),+ };+ }++ prepareCreateReturnDispatchParams(params) {+ delete params.controller;+ }++ getHeader() {+ return this.buildHeaderHtml([+ (() => {+ const a = document.createElement('a');+ a.textContent = this.translate('Administration');+ a.href = '#Admin';++ return a;+ })(),+ (() => {+ const a = document.createElement('a');+ a.textContent = this.translate('Pipelines', 'labels', 'Admin');+ a.href = `#Admin/pipelines`;++ return a;+ })(),+ (() => {+ const span = document.createElement('span');+ span.textContent = this.translate(this.targetEntityType, 'scopeNamesPlural');++ span.title = this.translate('clickToRefresh', 'messages');+ span.dataset.action = 'fullRefresh';+ span.style.cursor = 'pointer';+ span.style.userSelect = 'none';++ return span;+ })(),+ ]);+ }+}diff --git a/client/src/views/admin/pipelines/main.js b/client/src/views/admin/pipelines/main.jsnew file mode 100644index 0000000000..ca2fa5fdd2--- /dev/null+++ b/client/src/views/admin/pipelines/main.js@@ -0,0 +1,106 @@+/************************************************************************+ * This file is part of EspoCRM.+ *+ * EspoCRM – Open Source CRM application.+ * Copyright (C) 2014-2026 EspoCRM, Inc.+ * 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.+ ************************************************************************/++import MainView from 'views/main';++export default class AdminPipelinesMainView extends MainView {++ // language=Handlebars+ templateContent = `+ <div class="header page-header">{{{header}}}</div>+ <div class="record">+ {{#if entityTypeDataList.length}}+ <ul class="list-group list-group-panel">+ {{#each entityTypeDataList}}+ <li class="list-group-item">+ <a href="{{link}}">{{label}}</a>+ </li>+ {{/each}}+ </ul>+ {{else}}+ <div class="panel panel-info">+ <div class="panel-body">+ {{complexText noMessage}}+ </div>+ </div>+ {{/if}}+ </div>+ `++ /**+ * @private+ * @type {string[]}+ */+ entityTypeList++ data() {+ return {+ entityTypeDataList: this.getEntityTypeDataList(),+ noMessage: this.translate('noPipelinesEnabled', 'messages', 'Admin')+ }+ }++ setup() {+ this.createView('header', 'views/header', {});++ this.entityTypeList = this.getMetadata().getScopeEntityList()+ .filter(scope => this.getMetadata().get(`scopes.${scope}.pipelines`));+ }++ /**+ * @private+ * @return {Record[]}+ */+ getEntityTypeDataList() {+ return this.entityTypeList.map(it => {+ return {+ name: it,+ label: this.translate(it, 'scopeNamesPlural'),+ link: `#Admin/pipelines/scope=${it}`,+ };+ });+ }++ getHeader() {+ return this.buildHeaderHtml([+ (() => {+ const a = document.createElement('a');+ a.textContent = this.translate('Administration');+ a.href = '#Admin';++ return a;+ })(),+ (() => {+ const span = document.createElement('span');+ span.textContent = this.translate('Pipelines', 'labels', 'Admin');++ return span;+ })(),+ ]);+ }+}diff --git a/client/src/views/fields/color.js b/client/src/views/fields/color.jsnew file mode 100644index 0000000000..54f2eb63da--- /dev/null+++ b/client/src/views/fields/color.js@@ -0,0 +1,158 @@+/************************************************************************+ * This file is part of EspoCRM.+ *+ * EspoCRM – Open Source CRM application.+ * Copyright (C) 2014-2026 EspoCRM, Inc.+ * 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.+ ************************************************************************/++import BaseFieldView from 'views/fields/base';++/**+ * @since 9.4.0+ */+class ColorFieldView extends BaseFieldView {+ // language=Handlebars+ listTemplateContent = `+ {{#if isNotNull}}+ <span class="fas fa-square" style="color: {{color}}"></span>+ {{/if}}+ `++ // language=Handlebars+ detailTemplateContent = `+ {{#if isNotNull}}+ <span class="fas fa-square" style="color: {{color}}"></span>+ {{else}}+ {{#if valueIsSet}}+ <span class="none-value">{{translate 'None'}}</span>+ {{else}}+ <span class="loading-value"></span>+ {{/if}}+ {{/if}}+ `++ // language=Handlebars+ editTemplateContent = `+ <div class="btn-group">+ <button class="btn btn-default dropdown-toggle" data-toggle="dropdown">+ <span class="fas fa-square" style="color: {{color}}"></span>+ </button>+ <ul class="dropdown-menu">+ <li>+ <ul+ style="+ display: grid;+ grid-template-columns: 52px 52px 52px;+ padding-left: 0;+ "+ >+ {{#each colors}}+ <li style="list-style: none;">+ <a+ style="+ width: 100%;+ display: inline-block;+ text-align: center;+ padding: 2px;+ "+ class="dropdown-item"+ role="button"+ tabindex="0"+ data-action="selectColor{{#if selected}} active{{/if}}"+ data-value="{{value}}"+ ><span class="fas fa-square" style="color: {{color}}"></span></a>+ </li>+ {{/each}}+ </ul>+ </li>+ <li class="divider"></li>+ <li>+ <a+ class="dropdown-item"+ role="button"+ tabindex="0"+ data-action="selectColor{{#if isNull}} active{{/if}}"+ data-value=""+ style="text-align: center;"+ >{{translate 'None'}}</a>+ </li>+ </ul>+ </div>+ `++ // noinspection JSCheckFunctionSignatures+ data() {+ const value = this.model.attributes[this.name];++ if (this.isEditMode()) {+ const colors = [];++ let color = 'transparent';++ for (let i = 0; i < 9; i++) {+ colors.push({+ color: this.colors[i],+ selected: i === value,+ value: i,+ });++ if (i === value) {+ color = this.colors[i];+ }+ }++ return {+ colors: colors,+ color: color,+ isNull: value === null,+ };+ }++ if (this.isReadMode()) {+ return {+ valueIsSet: value !== undefined,+ isNotNull: value !== null,+ color: value != null ? this.colors[value] : 'transparent',+ };+ }++ return super.data();+ }++ setup() {+ /** @type {string[]} */+ this.colors = this.getHelper().themeManager.getParam('chartColorList') || [];++ this.addActionHandler('selectColor', (e, element) => {+ const value = element.dataset.value !== '' ?+ parseInt(element.dataset.value) : null;++ this.model.set(this.name, value, {ui: true});++ this.reRender();+ });+ }+}++export default ColorFieldView;diff --git a/client/src/views/fields/extra/pipeline-stage.js b/client/src/views/fields/extra/pipeline-stage.jsnew file mode 100644index 0000000000..c978ebf800--- /dev/null+++ b/client/src/views/fields/extra/pipeline-stage.js@@ -0,0 +1,200 @@+/************************************************************************+ * This file is part of EspoCRM.+ *+ * EspoCRM – Open Source CRM application.+ * Copyright (C) 2014-2026 EspoCRM, Inc.+ * 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.+ ************************************************************************/++import LinkFieldView from 'views/fields/link';+import Model from 'model';+import EnumFieldView from 'views/fields/enum';+import PipelinesHelper from 'helpers/misc/pipelines';++export default class PipelineFieldView extends LinkFieldView {++ // language=Handlebars+ listTemplateContent = `+ {{#if stringValue}}+ <span+ class="label label-md label-state label-{{style}}"+ title="{{stringValue}}"+ >{{stringValue}}</span>+ {{/if}}+ `++ // language=Handlebars+ detailTemplateContent = `+ {{#if stringValue}}+ <span+ class="label label-md label-state label-{{style}}"+ >{{stringValue}}</span>+ {{else}}+ {{#if valueIsSet}}+ <span class="none-value">{{translate 'None'}}</span>+ {{else}}+ <span class="loading-value"></span>+ {{/if}}+ {{/if}}+ `++ // language=Handlebars+ editTemplateContent = `+ <div data-sub-field="stage">{{{stageField}}}</div>+ `++ /**+ * @private+ * @type {{id: string, stages: {id: string, name: string, style: string|null}[]}[]}+ */+ pipelines++ data() {+ const data = super.data();++ data.stringValue = data.nameValue;++ const pipeline = this.getPipeline();++ data.style = 'default';++ if (pipeline && this.model.attributes[this.idName]) {+ const stage = pipeline.stages.find(it => it.id === this.model.attributes[this.idName]);++ data.style = stage?.style ?? 'default';+ }++ // noinspection JSValidateTypes+ return data;+ }++ setup() {+ super.setup();++ this.pipelines = new PipelinesHelper().get(this.entityType);++ this.setupSub();+ }++ /**+ * @private+ */+ setupSub() {+ this.subModel = new Model();++ const syncModels = () => {+ this.subModel.setMultiple({+ stage: this.model.attributes[this.idName],+ });+ };++ syncModels();++ this.listenTo(this.model, `change:${this.idName}`, (m, v, o) => {+ if (!o.ui || o.fromView && o.fromView !== this) {+ syncModels();+ }+ });++ this.listenTo(this.subModel, 'change', (m, o) => o.ui ? this.trigger('change') : null);++ this.listenTo(this.model, 'change:pipelineId pipeline-changed', async () => {+ await this.onEditModeSet()+ await this.reRender();+ });+ }++ /**+ * @private+ * @return {{id: string, stages: {id: string, name: string, style: string|null}[]}|null}+ */+ getPipeline() {+ const pipelineId = this.model.attributes.pipelineId;++ if (!pipelineId) {+ return null;+ }++ return this.pipelines.find(it => it.id === pipelineId) ?? null;+ }++ onEditModeSet() {+ const pipeline = this.getPipeline();++ const options = pipeline ? pipeline.stages.map(it => it.id) : [];++ const currentId = this.model.attributes[this.idName];++ if (!currentId || !pipeline) {+ options.unshift('');+ }++ if (currentId && !options.includes(currentId)) {+ options.push(currentId);+ }++ const translatedOptions = {};+ const style = {};++ if (pipeline) {+ pipeline.stages.forEach(it => {+ translatedOptions[it.id] = it.name;+ style[it.id] = it.style;+ });+ }++ if (currentId && !translatedOptions[currentId]) {+ translatedOptions[currentId] = this.model.attributes[this.idName] ?? currentId;+ }++ this.enumView = new EnumFieldView({+ name: 'stage',+ model: this.subModel,+ mode: 'edit',+ params: {+ options,+ translatedOptions,+ style,+ },+ });++ return this.assignView('stageField', this.enumView, '[data-sub-field="stage"]');+ }++ fetch() {+ const id = this.subModel.attributes.stage;+ let name = null;++ const pipeline = this.getPipeline();++ if (id && pipeline) {+ name = pipeline.stages.find(it => it.id === id)?.name ?? null;+ }++ // noinspection JSValidateTypes+ return {+ [this.idName]: id,+ [this.nameName]: name ?? id,+ };+ }+}diff --git a/client/src/views/fields/extra/pipeline.js b/client/src/views/fields/extra/pipeline.jsnew file mode 100644index 0000000000..c1c93f095d--- /dev/null+++ b/client/src/views/fields/extra/pipeline.js@@ -0,0 +1,235 @@+/************************************************************************+ * This file is part of EspoCRM.+ *+ * EspoCRM – Open Source CRM application.+ * Copyright (C) 2014-2026 EspoCRM, Inc.+ * 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.+ ************************************************************************/++import LinkFieldView from 'views/fields/link';+import {inject} from 'di';+import EnumFieldView from 'views/fields/enum';+import Model from 'model';+import PipelinesHelper from 'helpers/misc/pipelines';+import ThemeManager from 'theme-manager';++export default class PipelineFieldView extends LinkFieldView {++ // language=Handlebars+ listTemplateContent = `+ {{~#if stringValue~}}+ <span+ class="color-icon fas fa-square text-soft"+ style=" {{#if color}} color: {{color}}; {{/if}} "+ ></span><span style="user-select: none"> </span>+ {{~#if 1}}{{/if~}}+ <span+ class=""+ title="{{stringValue}}"+ >{{stringValue}}</span>+ {{/if}}+ `++ // language=Handlebars+ detailTemplateContent = `+ {{~#if stringValue~}}+ <span+ class="color-icon fas fa-square text-soft"+ style=" {{#if color}} color: {{color}}; {{/if}} "+ ></span><span style="user-select: none"> </span>+ {{~#if 1}}{{/if~}}+ <span+ class=""+ >{{stringValue}}</span>+ {{else}}+ {{#if valueIsSet}}+ <span class="none-value">{{translate 'None'}}</span>+ {{else}}+ <span class="loading-value"></span>+ {{/if}}+ {{/if}}+ `++ // language=Handlebars+ editTemplateContent = `+ <div data-sub-field="pipeline">{{{pipelineField}}}</div>+ `++ /**+ * @private+ * @type {Model}+ */+ subModel++ /**+ * @private+ * @type {EnumFieldView}+ */+ enumView++ /**+ * @private+ * @type {{id: string, name: string, color: number|null}[]}+ */+ pipelines++ /**+ * @private+ * @type {Record<string, string>}+ */+ translatedOptions++ /**+ * @private+ * @type {Record<string, number|null>}+ */+ colorMap++ /**+ * @private+ * @type {ThemeManager}+ */+ @inject(ThemeManager)+ themeManager++ data() {+ const data = super.data();++ data.stringValue = data.nameValue;++ if (this.model.attributes[this.idName]) {+ data.color = this.colorMap[this.model.attributes[this.idName]] ?? null;+ }++ // noinspection JSValidateTypes+ return data;+ }++ setup() {+ super.setup();++ this.setupPipelines();++ const translatedOptions = {};++ for (const it of this.pipelines) {+ translatedOptions[it.id] = it.name;+ }++ this.translatedOptions = translatedOptions;++ this.setupSub();+ }++ /**+ * @private+ */+ setupPipelines() {+ this.pipelines = new PipelinesHelper().get(this.entityType);++ /** @type {string[]} */+ const colors = this.themeManager.getParam('chartColorList') || [];++ this.colorMap = this.pipelines.reduce((o, it) => {+ let color = null;++ if (it.color != null) {+ color = colors[it.color] ?? null;+ }++ o[it.id] = color;++ return o;+ }, {});+ }++ /**+ * @private+ */+ setupSub() {+ this.subModel = new Model();++ const syncModels = () => {+ this.subModel.setMultiple({+ pipeline: this.model.attributes[this.idName],+ });+ };++ syncModels();++ this.listenTo(this.model, `change:${this.idName}`, (m, v, o) => {+ if (!o.ui || o.fromView && o.fromView !== this) {+ syncModels();+ }+ });++ this.listenTo(this.subModel, 'change', (m, o) => o.ui ? this.trigger('change') : null);+ }++ onEditModeSet() {+ const options = this.pipelines.map(it => it.id);++ const currentId = this.model.attributes[this.idName];++ if (!currentId) {+ options.unshift('');+ }++ if (currentId && !options.includes(currentId)) {+ options.push(currentId);+ }++ const translatedOptions = {...this.translatedOptions};++ if (currentId && !translatedOptions[currentId]) {+ translatedOptions[currentId] = this.model.attributes[this.idName] ?? currentId;+ }++ this.enumView = new EnumFieldView({+ name: 'pipeline',+ model: this.subModel,+ mode: 'edit',+ params: {+ options,+ translatedOptions,+ },+ optionItemHandler: it => {+ return {+ color: this.colorMap[it.value],+ };+ },+ });++ return this.assignView('pipelineField', this.enumView, '[data-sub-field="pipeline"]');+ }++ fetch() {+ const id = this.subModel.attributes.pipeline;++ // noinspection JSValidateTypes+ return {+ [this.idName]: id,+ [this.nameName]: id ? (this.translatedOptions[id] ?? id) : null,+ };+ }+}diff --git a/client/src/views/list.js b/client/src/views/list.jsindex f60c9c912f..49cd2e628e 100644--- a/client/src/views/list.js+++ b/client/src/views/list.js@@ -32,6 +32,7 @@ import MainView from 'views/main';import SearchManager from 'search-manager';import RecordModal from 'helpers/record-modal';import Utils from 'utils';+import PipelinesHelper from 'helpers/misc/pipelines';/*** A list view.@@ -284,12 +285,21 @@ class ListView extends MainView {if (viewModeList) {this.viewModeList = viewModeList;- }- else {+ } else {this.viewModeList = [this.MODE_LIST];- if (this.getMetadata().get(['clientDefs', this.scope, 'kanbanViewMode'])) {- if (!~this.viewModeList.indexOf(this.MODE_KANBAN)) {+ // @todo Mode defs in metadata. Availability is checked in a handler class.++ if (+ this.getMetadata().get(`clientDefs.${this.scope}.kanbanViewMode`) &&+ !this.viewModeList.includes(this.MODE_KANBAN)+ ) {+ const pipelinesHelper = new PipelinesHelper();++ if (+ !pipelinesHelper.isEnabled(this.scope) ||+ pipelinesHelper.get(this.scope).length+ ) {this.viewModeList.push(this.MODE_KANBAN);}}diff --git a/client/src/views/modals/kanban-move-over.js b/client/src/views/modals/kanban-move-over.jsindex 37f52ddeaf..4456164f48 100644--- a/client/src/views/modals/kanban-move-over.js+++ b/client/src/views/modals/kanban-move-over.js@@ -27,6 +27,8 @@************************************************************************/import ModalView from 'views/modal';+import OptionsProvider from 'helpers/field/options-provider';+import PipelinesHelper from 'helpers/misc/pipelines';class KanbanMoveOverModalView extends ModalView {@@ -75,22 +77,42 @@ class KanbanMoveOverModalView extends ModalView {this.buttonList = [{name: 'cancel',- label: 'Cancel'- }+ label: 'Cancel',+ },];+ this.setupGroupDataList();+ }++ /**+ * @private+ */+ setupGroupDataList() {+ if (this.options.pipelineId) {+ const pipeline = new PipelinesHelper().get(this.scope)+ .find(it => it.id === this.options.pipelineId);- this.optionDataList = [];+ const stages = pipeline?.stages- (- this.getMetadata()- .get(['entityDefs', this.scope, 'fields', this.statusField, 'options']) || []- )- .forEach((item) => {- this.optionDataList.push({- value: item,- label: this.getLanguage().translateOption(item, this.statusField, this.scope),- });++ this.optionDataList = stages.map(it => {+ return {+ value: it.id,+ label: it.name,+ };});++ return;+ }++ const options = new OptionsProvider().get(this.scope, this.statusField)+ .filter(it => it.name);++ this.optionDataList = options.map(it => {+ return {+ value: it.name,+ label: it.label,+ };+ });}/**diff --git a/client/src/views/pipeline-stage/fields/mapped-status.js b/client/src/views/pipeline-stage/fields/mapped-status.jsnew file mode 100644index 0000000000..4bcfc8e1b3--- /dev/null+++ b/client/src/views/pipeline-stage/fields/mapped-status.js@@ -0,0 +1,76 @@+/************************************************************************+ * This file is part of EspoCRM.+ *+ * EspoCRM – Open Source CRM application.+ * Copyright (C) 2014-2026 EspoCRM, Inc.+ * 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.+ ************************************************************************/++import EnumFieldView from 'views/fields/enum';++// noinspection JSUnusedGlobalSymbols+export default class PipelineStageMappedStatusFieldView extends EnumFieldView {++ setupOptions() {+ const entityType = this.model.attributes.entityType;+ const field = this.model.attributes.field;++ if (!entityType || !field) {+ return;+ }++ let sourceEntityType = entityType;+ let sourceField = field;++ const params = this.getMetadata().get(`entityDefs.${entityType}.fields.${field}`) ?? {};++ let optionsPath = params.optionsPath;+ const optionsReference = params.optionsReference;+ /** @var string[] */+ let options = params.options ?? [];+ const style = params.style;++ if (!optionsPath && optionsReference) {+ const [refEntityType, refField] = optionsReference.split('.');++ optionsPath = `entityDefs.${refEntityType}.fields.${refField}.options`;++ sourceEntityType = refEntityType;+ sourceField = refField;+ }++ if (optionsPath) {+ options = this.getMetadata().get(optionsPath);+ }++ options = options.filter(it => it);++ this.params.options = Espo.Utils.clone(options);+ this.styleMap = style ?? {};++ const pairs = this.params.options+ .map(item => [item, this.getLanguage().translateOption(item, sourceField, sourceEntityType)])++ this.translatedOptions = Object.fromEntries(pairs);+ }+}diff --git a/client/src/views/pipeline/detail.js b/client/src/views/pipeline/detail.jsnew file mode 100644index 0000000000..6df741b5d4--- /dev/null+++ b/client/src/views/pipeline/detail.js@@ -0,0 +1,38 @@+/************************************************************************+ * This file is part of EspoCRM.+ *+ * EspoCRM – Open Source CRM application.+ * Copyright (C) 2014-2026 EspoCRM, Inc.+ * 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.+ ************************************************************************/++import DetailView from 'views/detail';++export default class extends DetailView {++ setup() {+ this.rootUrl = '#Admin/pipelines';++ super.setup();+ }+}diff --git a/client/src/views/pipeline/fields/entity-type.js b/client/src/views/pipeline/fields/entity-type.jsnew file mode 100644index 0000000000..9e26885668--- /dev/null+++ b/client/src/views/pipeline/fields/entity-type.js@@ -0,0 +1,40 @@+/************************************************************************+ * This file is part of EspoCRM.+ *+ * EspoCRM – Open Source CRM application.+ * Copyright (C) 2014-2026 EspoCRM, Inc.+ * 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.+ ************************************************************************/++import EntityTypeFieldView from 'views/fields/entity-type';++export default class extends EntityTypeFieldView {++ setup() {+ super.setup();++ if (this.model.attributes.entityType && !this.isListMode() && !this.isSearchMode()) {+ this.setReadOnly(true);+ }+ }+}diff --git a/client/src/views/pipeline/fields/field.js b/client/src/views/pipeline/fields/field.jsnew file mode 100644index 0000000000..bf8f0153fe--- /dev/null+++ b/client/src/views/pipeline/fields/field.js@@ -0,0 +1,71 @@+/************************************************************************+ * This file is part of EspoCRM.+ *+ * EspoCRM – Open Source CRM application.+ * Copyright (C) 2014-2026 EspoCRM, Inc.+ * 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.+ ************************************************************************/++import EnumFieldView from 'views/fields/enum';++export default class extends EnumFieldView {++ getAttributeList() {+ return [+ ...super.getAttributeList(),+ 'entityType',+ ];+ }++ setup() {+ super.setup();++ this.model.onChange({+ owner: this,+ attributes: ['entityType'],+ callback: () => this.setupTranslation(),+ });+ }++ setupTranslation() {+ const entityType = this.model.attributes.entityType;++ if (!entityType) {+ this.setTranslatedOptions({});++ return;+ }++ const field = this.getMetadata().get(`scopes.${entityType}.statusField`);++ if (!field) {+ this.setTranslatedOptions({});++ return;+ }++ this.setTranslatedOptions({+ [field]: this.translate(field, 'fields', entityType),+ });+ }+}diff --git a/client/src/views/pipeline/record/panels/stages.js b/client/src/views/pipeline/record/panels/stages.jsnew file mode 100644index 0000000000..c8a60fd9f0--- /dev/null+++ b/client/src/views/pipeline/record/panels/stages.js@@ -0,0 +1,39 @@+/************************************************************************+ * This file is part of EspoCRM.+ *+ * EspoCRM – Open Source CRM application.+ * Copyright (C) 2014-2026 EspoCRM, Inc.+ * 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.+ ************************************************************************/++import RelationshipPanelView from 'views/record/panels/relationship';++// noinspection JSUnusedGlobalSymbols+export default class extends RelationshipPanelView {++ setup() {+ this.recordsPerPage = this.getConfig().get('recordsPerPage');++ super.setup();+ }+}diff --git a/client/src/views/record/kanban.js b/client/src/views/record/kanban.jsindex 7dc1bc0034..066ef2b36a 100644--- a/client/src/views/record/kanban.js+++ b/client/src/views/record/kanban.js@@ -30,6 +30,10 @@import ListRecordView from 'views/record/list';import RecordModal from 'helpers/record-modal';+import {inject} from 'di';+import AppParams from 'app-params';+import KanbanPipelineDropdownView from 'views/record/kanban/pipeline-dropdown';+import PipelinesHelper from 'helpers/misc/pipelines';/*** A kanban record view.@@ -96,6 +100,29 @@ class KanbanRecordView extends ListRecordView {*/styleMap+ /**+ * @private+ * @type {boolean}+ */+ usePipeline = false++ /**+ * @private+ * @type {string|null}+ */+ currentPipelineId = null++ /**+ * @private+ * @type {{+ * id: string,+ * name: string,+ * stages: {id: string, name: string, style: string|null}[],+ * color: number|null,+ * }[]}+ */+ pipelines+/*** Layout item definitions.*@@ -274,7 +301,8 @@ class KanbanRecordView extends ListRecordView {this.displayTotalCount ||this.buttonList.length &&!this.buttonsDisabled ||- !!this._listSettingsHelper+ !!this._listSettingsHelper ||+ this.usePipeline);// noinspection JSValidateTypes@@ -291,6 +319,7 @@ class KanbanRecordView extends ListRecordView {isEmptyList: this.collection.models.length === 0,totalCountFormatted: this.getNumberUtil().formatInt(this.collection.total),noDataDisabled: this._renderEmpty,+ usePipeline: this.usePipeline,};}@@ -373,8 +402,16 @@ class KanbanRecordView extends ListRecordView {}}+ if (!this.options.statusField && this.getMetadata().get(`scopes.${this.scope}.pipelines`)) {+ this.usePipeline = true;+ }+this.setupStatusField();+ if (this.usePipeline) {+ this.setupPipeline();+ }+this.seedCollection = this.collection.clone();this.seedCollection.reset();this.seedCollection.url = this.scope;@@ -445,16 +482,94 @@ class KanbanRecordView extends ListRecordView {this.hasStars = this.getMetadata().get(`scopes.${this.entityType}.stars`) || false;}+ /**+ * @private+ */+ setupPipeline() {+ this.pipelines = new PipelinesHelper().get(this.entityType);++ this.currentPipelineId = this.getStorage().get('state', this.buildPipelineIdStorageKey());++ if (!this.currentPipelineId) {+ this.currentPipelineId = this.pipelines[0]?.id ?? null;+ }++ if (this.currentPipelineId && !this.pipelines.find(it => it.id === this.currentPipelineId)) {+ this.currentPipelineId = null;+ }++ this.setPipelineWhere();+ this.setupPipelineDropdown();+ }++ /**+ * @private+ */+ setPipelineWhere() {+ if (!this.currentPipelineId) {+ this.collection.whereFunction = null;++ return;+ }++ this.collection.whereFunction = () => {+ return [+ {+ type: 'equals',+ attribute: 'pipelineId',+ value: this.currentPipelineId,+ }+ ];+ };+ }++ /**+ * @private+ */+ setupPipelineDropdown() {+ const state = {+ pipelineId: this.currentPipelineId,+ pipelines: this.pipelines,+ };++ const view = new KanbanPipelineDropdownView({+ state: state,+ onChange: async id => {+ this.currentPipelineId = id;+ state.pipelineId = id;++ this.setPipelineWhere();++ this.getStorage().set('state', this.buildPipelineIdStorageKey(), id);++ await view.reRender();++ Espo.Ui.notifyWait();++ await this.collection.fetch({maxSize: this.collection.maxSize});++ Espo.Ui.notify();+ },+ });++ this.assignView('pipelineDropdown', view);+ }+/*** @private*/setupStatusField() {this.statusField = this.options.statusField || this.getMetadata().get(['scopes', this.scope, 'statusField']);+ if (this.usePipeline) {+ this.statusField = 'pipelineStageId';+ }+if (!this.statusField) {throw new Error(`No status field for entity type '${this.scope}'.`);}+ // @todo Use options-provider.this.styleMap = /** @type {Record.<string, string>} */this.getMetadata().get(`entityDefs.${this.scope}.fields.${this.statusField}.style`) ?? {};@@ -1255,6 +1370,7 @@ class KanbanRecordView extends ListRecordView {this.createView('moveOverDialog', 'views/modals/kanban-move-over', {model: model,statusField: this.statusField,+ pipelineId: this.currentPipelineId,}, view => {view.render();});@@ -1318,7 +1434,13 @@ class KanbanRecordView extends ListRecordView {return this.getCreateAttributes(group);}- return Promise.resolve({[this.statusField]: group});+ const attributes = {[this.statusField]: group};++ if (this.usePipeline) {+ attributes.pipelineId = this.currentPipelineId;+ }++ return Promise.resolve(attributes);};const attributes = await getCreateAttributes();@@ -1523,6 +1645,14 @@ class KanbanRecordView extends ListRecordView {setCanReOrder(canReOrder) {this.orderDisabled = !canReOrder;}++ /**+ * @private+ * @return {string}+ */+ buildPipelineIdStorageKey() {+ return 'kanban-pipelineId-' + this.scope;+ }}export default KanbanRecordView;diff --git a/client/src/views/record/kanban/pipeline-dropdown.js b/client/src/views/record/kanban/pipeline-dropdown.jsnew file mode 100644index 0000000000..760e2a8630--- /dev/null+++ b/client/src/views/record/kanban/pipeline-dropdown.js@@ -0,0 +1,164 @@+/************************************************************************+ * This file is part of EspoCRM.+ *+ * EspoCRM – Open Source CRM application.+ * Copyright (C) 2014-2026 EspoCRM, Inc.+ * 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.+ ************************************************************************/++import View from 'view';+import {inject} from 'di';+import ThemeManager from 'theme-manager';++export default class KanbanPipelineDropdownView extends View {++ // language=Handlebars+ templateContent = `+ <button+ class="btn btn-text dropdown-toggle btn-s-wide"+ data-toggle="dropdown"+ title="{{translate 'pipeline' category='fields'}}"+ >+ {{~#if 0}}{{/if~}}+ <span+ class="color-icon fas fa-square text-soft"+ style=" {{#if color}} color: {{color}} {{/if}} "+ ></span>+ <span>{{name}}</span>+ <span class="caret"></span>+ </button>+ <ul class="dropdown-menu">+ {{#each pipelines}}+ <li>+ <a+ role="button"+ data-id="{{id}}"+ data-action="selectPipeline"+ >++ {{#if selected}}+ <span class="fas fa-check check-icon pull-right"></span>+ {{/if}}+ <div class="{{#if active}} text-bold text-soft{{/if}}">+ {{~#if 0}}{{/if~}}+ <span+ class="color-icon fas fa-square text-soft"+ style="+ {{#if color}} color: {{color}}; {{/if}}+ padding-right: var(--4px);+ "+ ></span>+ {{name}}+ </div>+ </a>+ </li>+ {{/each}}+ </ul>+ `++ /**+ * @private+ * @type {ThemeManager}+ */+ @inject(ThemeManager)+ themeManager++ /**+ * @private+ * @type {Record<string, number|null>}+ */+ colorMap++ /**+ *+ * @param {{+ * state: {+ * pipelineId: string,+ * pipelines: {+ * id: string,+ * name: string,+ * color: number|null,+ * }[],+ * },+ * onChange: function(string),+ * }} options+ */+ constructor(options) {+ super(options);++ this.options = options;++ /** @private */+ this.state = options.state;+ }++ data() {+ const id = this.state.pipelineId;++ const name = this.state.pipelines.find(it => it.id === id)?.name;+ const color = id ? this.colorMap[id] : null;++ const pipelines = this.state.pipelines.map(it => ({+ ...it,+ selected: id === it.id,+ color: this.colorMap[it.id] ?? null,+ }));++ return {+ name: name ?? id,+ pipelines: pipelines,+ color: color ?? null,+ };+ }++ setup() {+ this.addActionHandler('selectPipeline', (e, target) => this.selectPipeline(target.dataset.id));++ /** @type {string[]} */+ const colors = this.themeManager.getParam('chartColorList') || [];++ this.colorMap = this.state.pipelines.reduce((o, it) => {+ let color = null;++ if (it.color != null) {+ color = colors[it.color] ?? null;+ }++ o[it.id] = color;++ return o;+ }, {});+ }++ /**+ * @private+ * @param {string} id+ */+ selectPipeline(id) {+ if (this.state.pipelineId === id) {+ return;+ }++ this.options.onChange(id);+ }+}diff --git a/client/src/views/record/panels/relationship.js b/client/src/views/record/panels/relationship.jsindex dec2fa3b9b..037ec4c1e4 100644--- a/client/src/views/record/panels/relationship.js+++ b/client/src/views/record/panels/relationship.js@@ -91,7 +91,10 @@ class RelationshipPanelView extends BottomPanelView {noCreateScopeList = ['User', 'Team', 'Role', 'Portal']/**- * @private+ * Records per page. If not set, the value from config is used.+ *+ * @protected+ * @type {number|null}*/recordsPerPage = nulldiff --git a/tests/integration/Espo/Tools/Pipeline/PipelineTest.php b/tests/integration/Espo/Tools/Pipeline/PipelineTest.phpnew file mode 100644index 0000000000..51653d2c05--- /dev/null+++ b/tests/integration/Espo/Tools/Pipeline/PipelineTest.php@@ -0,0 +1,214 @@+<?php+/************************************************************************+ * This file is part of EspoCRM.+ *+ * EspoCRM – Open Source CRM application.+ * Copyright (C) 2014-2026 EspoCRM, Inc.+ * 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 tests\integration\Espo\Tools\Pipeline;++use Espo\Classes\AppParams\Pipelines;+use Espo\Core\Acl\Table;+use Espo\Core\Exceptions\BadRequest;+use Espo\Core\Field\Date;+use Espo\Core\Name\Field;+use Espo\Core\Record\CreateParams;+use Espo\Core\Record\DeleteParams;+use Espo\Core\Record\ServiceContainer;+use Espo\Core\Record\UpdateParams;+use Espo\Entities\Pipeline;+use Espo\Entities\PipelineStage;+use Espo\Entities\Role;+use Espo\Entities\Team;+use Espo\Modules\Crm\Entities\Opportunity;+use Espo\Tools\EntityManager\EntityManager as EntityManagerTool;+use tests\integration\Core\BaseTestCase;++class PipelineTest extends BaseTestCase+{+ /**+ * @noinspection PhpUnhandledExceptionInspection+ */+ public function testPipeline1(): void+ {+ $this->initPipeline(Opportunity::ENTITY_TYPE);++ $em = $this->getEntityManager();++ $role = $em->getRDBRepositoryByClass(Role::class)->getNew();+ $role+ ->set(Field::NAME, 'Test')+ ->setRawData([+ Opportunity::ENTITY_TYPE => [+ Table::ACTION_EDIT => Table::LEVEL_TEAM,+ ],+ ]);+ $em->saveEntity($role);++ $team = $em->createEntity(Team::ENTITY_TYPE, [+ Field::NAME => 'Test',+ 'rolesIds' => [$role->getId()],+ ]);++ $user1 = $this->createUser([+ 'userName' => 'test-1',+ 'teamsIds' => [$team->getId()],+ ]);++ $pipelineService = $this->getContainer()+ ->getByClass(ServiceContainer::class)+ ->getByClass(Pipeline::class);++ $pipelineStageService = $this->getContainer()+ ->getByClass(ServiceContainer::class)+ ->getByClass(PipelineStage::class);++ $oppService = $this->getContainer()+ ->getByClass(ServiceContainer::class)+ ->getByClass(Opportunity::class);++ //++ $pipeline1 = $pipelineService->create((object) [+ Field::NAME => 'Test 1',+ Pipeline::FIELD_ENTITY_TYPE => Opportunity::ENTITY_TYPE,+ Pipeline::FIELD_IS_AVAILABLE_FOR_ALL => false,+ ], CreateParams::create());++ $this->assertCount(6, $pipeline1->getStages());++ //++ $pipeline2 = $pipelineService->create((object) [+ Field::NAME => 'Test 2',+ Pipeline::FIELD_ENTITY_TYPE => Opportunity::ENTITY_TYPE,+ Pipeline::FIELD_IS_AVAILABLE_FOR_ALL => false,+ Field::TEAMS . 'Ids' => [$team->getId()],+ ], CreateParams::create());++ foreach ($pipeline2->getStages() as $stage) {+ $pipelineStageService->delete($stage->getId(), DeleteParams::create());+ }++ $pipelineStageService->create((object) [+ Field::NAME => 'Open',+ PipelineStage::ATTR_PIPELINE_ID => $pipeline2->getId(),+ PipelineStage::FIELD_MAPPED_STATUS => 'Prospecting',+ ], CreateParams::create());++ $pipelineStageService->create((object) [+ Field::NAME => 'Closed Won',+ PipelineStage::ATTR_PIPELINE_ID => $pipeline2->getId(),+ PipelineStage::FIELD_MAPPED_STATUS => Opportunity::STAGE_CLOSED_WON,+ ], CreateParams::create());++ $pipelineStageService->create((object) [+ Field::NAME => 'Closed Lost',+ PipelineStage::ATTR_PIPELINE_ID => $pipeline2->getId(),+ PipelineStage::FIELD_MAPPED_STATUS => Opportunity::STAGE_CLOSED_LOST,+ ], CreateParams::create());++ $thrown = false;++ try {+ // Non-existing status.+ $pipelineStageService->create((object) [+ Field::NAME => 'Test',+ PipelineStage::ATTR_PIPELINE_ID => $pipeline2->getId(),+ PipelineStage::FIELD_MAPPED_STATUS => 'Test',+ ], CreateParams::create());+ } catch (BadRequest) {+ $thrown = true;+ }++ $this->assertTrue($thrown);++ $em->refreshEntity($pipeline2);++ $this->assertCount(3, $pipeline2->getStages());++ //++ $opp = $oppService->create((object) [+ Field::NAME => 'Opp 1',+ Field::PIPELINE . 'Id' => $pipeline1->getId(),+ Field::PIPELINE_STAGE . 'Id' => $pipeline1->getStages()[0]->getId(),+ Opportunity::FIELD_CLOSED_DATE => Date::fromString('2026-01-01')->toString(),+ Opportunity::FIELD_AMOUNT => 1000,+ ], CreateParams::create());++ $opp = $oppService->update($opp->getId(), (object) [+ Field::PIPELINE . 'Id' => $pipeline2->getId(),+ Field::PIPELINE_STAGE . 'Id' => $pipeline2->getStages()[0]->getId(),+ ], UpdateParams::create());++ $this->assertEquals('Prospecting', $opp->getStage());++ //++ $opp = $oppService->create((object) [+ Field::NAME => 'Opp 2',+ Field::PIPELINE . 'Id' => $pipeline1->getId(),+ Field::PIPELINE_STAGE . 'Id' => $pipeline1->getStages()[4]->getId(),+ Opportunity::FIELD_CLOSED_DATE => Date::fromString('2026-01-01')->toString(),+ Opportunity::FIELD_AMOUNT => 1000,+ ], CreateParams::create());++ $this->assertEquals(Opportunity::STAGE_CLOSED_WON, $opp->getStage());++ //++ $pipelinesParam = $this->getInjectableFactory()->create(Pipelines::class);++ $pipelines = $pipelinesParam->get();++ $this->assertCount(2, $pipelines[Opportunity::ENTITY_TYPE]);++ //++ $this->auth($user1->getUserName());+ $this->reCreateApplication();++ $pipelinesParam = $this->getInjectableFactory()->create(Pipelines::class);++ $pipelines = $pipelinesParam->get();++ $this->assertCount(1, $pipelines[Opportunity::ENTITY_TYPE]);+ }++ /**+ * @noinspection PhpUnhandledExceptionInspection+ * @noinspection PhpArrayKeyDoesNotMatchArrayShapeInspection+ * @noinspection PhpSameParameterValueInspection+ */+ private function initPipeline(string $entityType): void+ {+ $entityManager = $this->getInjectableFactory()->create(EntityManagerTool::class);++ $entityManager->update($entityType, [+ 'pipelines' => true+ ]);+ }+}