From bedf805456c320a74bea40d192380aea5499e3b3 Mon Sep 17 00:00:00 2001 From: Yuri Kuznetsov Date: Wed, 25 Jun 2025 10:12:15 +0300 Subject: [PATCH] email to case relate replies --- application/Espo/Entities/Email.php | 2 + .../Classes/RecordHooks/Case/AfterCreate.php | 41 +++++++++++++++++-- 2 files changed, 40 insertions(+), 3 deletions(-) diff --git a/application/Espo/Entities/Email.php b/application/Espo/Entities/Email.php index 2be63a27c6..4d7b1d8c51 100644 --- a/application/Espo/Entities/Email.php +++ b/application/Espo/Entities/Email.php @@ -72,6 +72,8 @@ class Email extends Entity private const ATTR_BODY_PLAIN = 'bodyPlain'; + public const LINK_REPLIES = 'replies'; + public function get(string $attribute): mixed { if ($attribute === 'subject') { diff --git a/application/Espo/Modules/Crm/Classes/RecordHooks/Case/AfterCreate.php b/application/Espo/Modules/Crm/Classes/RecordHooks/Case/AfterCreate.php index e41931e416..580373e8b7 100644 --- a/application/Espo/Modules/Crm/Classes/RecordHooks/Case/AfterCreate.php +++ b/application/Espo/Modules/Crm/Classes/RecordHooks/Case/AfterCreate.php @@ -30,6 +30,7 @@ namespace Espo\Modules\Crm\Classes\RecordHooks\Case; use Espo\Core\Acl; +use Espo\Core\Name\Field; use Espo\Core\Record\Hook\SaveHook; use Espo\Entities\Email; use Espo\Modules\Crm\Entities\Account; @@ -39,15 +40,21 @@ use Espo\Modules\Crm\Entities\Lead; use Espo\ORM\Entity; use Espo\ORM\EntityManager; +use RuntimeException; + /** * @implements SaveHook * @noinspection PhpUnused */ class AfterCreate implements SaveHook { + private const EMAIL_REPLY_LEVEL = 3; + private const EMAIL_REPLY_LIMIT = 2; + private const EMAIL_REPLY_LIMIT_SECOND = 1; + public function __construct( private EntityManager $entityManager, - private Acl $acl + private Acl $acl, ) {} public function process(Entity $entity): void @@ -61,7 +68,16 @@ class AfterCreate implements SaveHook $email = $this->entityManager->getRDBRepositoryByClass(Email::class)->getById($emailId); - if (!$email || !$this->acl->checkEntityRead($email)) { + if (!$email) { + return; + } + + $this->changeEmailParent($email, $entity); + } + + private function changeEmailParent(Email $email, CaseObj $entity, int $level = 0): void + { + if (!$this->acl->checkEntityRead($email)) { return; } @@ -77,7 +93,26 @@ class AfterCreate implements SaveHook } $email->setParent($entity); - $this->entityManager->saveEntity($email); + + if ($level === self::EMAIL_REPLY_LEVEL) { + return; + } + + $limit = $level === 0 ? self::EMAIL_REPLY_LIMIT : self::EMAIL_REPLY_LIMIT_SECOND; + + $replies = $this->entityManager + ->getRelation($email, Email::LINK_REPLIES) + ->limit(0, $limit) + ->order(Field::CREATED_AT) + ->find(); + + foreach ($replies as $reply) { + if (!$reply instanceof Email) { + throw new RuntimeException(); + } + + $this->changeEmailParent($reply, $entity, $level + 1); + } } }