snapshot of https://github.com/espocrm/espocrm.git (master, 2026-09-18; blobs > 131072B omitted)
Some checks failed
Test / Test on PHP 8.3 (push) Failing after 5s
Test / Test on PHP 8.4 (push) Failing after 4s
Test / Test on PHP 8.5 (push) Failing after 3s
TypeScript static analysis / TypeScript check (push) Failing after 14s
Test Integration on MySQL / Test on PHP 8.3 (push) Failing after 1s
Test Integration on MySQL / Test on PHP 8.5 (push) Failing after 1s
Test Integration on PostgreSQL / Test on PHP 8.4 fix (push) Failing after 1s
Test Integration on PostgreSQL / Test on PHP 8.4 master (push) Failing after 1s

This commit is contained in:
upstream-mirror
2026-09-18 04:19:15 +05:00
commit 7cc7e6b4f3
10077 changed files with 900756 additions and 0 deletions

View File

@@ -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\Tools\Notification\Api;
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\Tools\Notification\GroupAllService;
/**
* @noinspection PhpUnused
*/
class DeleteGroup implements Action
{
public function __construct(
private GroupAllService $service,
) {}
public function process(Request $request): Response
{
$id = $request->getRouteParam('id') ?? throw new BadRequest();
$this->service->remove($id);
return ResponseComposer::json(true);
}
}

View File

@@ -0,0 +1,60 @@
<?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\Notification\Api;
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\Record\EntityProvider;
use Espo\Entities\Notification;
use Espo\Tools\Notification\GroupService;
class GetGroup implements Action
{
public function __construct(
private EntityProvider $entityProvider,
private GroupService $service,
) {}
public function process(Request $request): Response
{
$id = $request->getRouteParam('id') ?? throw new BadRequest();
$notification = $this->entityProvider->getByClass(Notification::class, $id);
$collection = $this->service->get($notification);
return ResponseComposer::json(
$collection->toApiOutput()
);
}
}

View File

@@ -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\Notification\Api;
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\Record\SearchParamsFetcher;
use Espo\Core\Select\Where\Item as WhereItem;
use Espo\Entities\Notification;
use Espo\Tools\Notification\GroupAllService;
/**
* @noinspection PhpUnused
*/
class GetGroupAll implements Action
{
public function __construct(
private GroupAllService $service,
private SearchParamsFetcher $searchParamsFetcher,
) {}
public function process(Request $request): Response
{
$type = $request->getQueryParam('type') ?? throw new BadRequest("No `type`.");
$id = $request->getQueryParam('id') ?? throw new BadRequest("No `id`.");
$searchParams = $this->searchParamsFetcher->fetch($request);
$beforeNumber = $request->getQueryParam('beforeNumber');
if ($beforeNumber) {
$searchParams = $searchParams
->withWhereAdded(
WhereItem
::createBuilder()
->setAttribute(Notification::ATTR_NUMBER)
->setType(WhereItem\Type::LESS_THAN)
->setValue($beforeNumber)
->build()
);
}
$collection = $this->service->get($type, $id, $searchParams);
return ResponseComposer::json(
$collection->toApiOutput()
);
}
}

View File

@@ -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\Tools\Notification\Api;
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\Tools\Notification\GroupAllService;
/**
* @noinspection PhpUnused
*/
class MarkGroupRead implements Action
{
public function __construct(
private GroupAllService $service,
) {}
public function process(Request $request): Response
{
$id = $request->getRouteParam('id') ?? throw new BadRequest();
$this->service->markRead($id);
return ResponseComposer::json(true);
}
}

View File

@@ -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\Tools\Notification;
use Espo\Core\Acl\AssignmentChecker\Helper;
use Espo\Core\Field\LinkParent;
use Espo\Core\Name\Field;
use Espo\Core\Notification\AssignmentNotificator\Params;
use Espo\Core\Notification\UserEnabledChecker;
use Espo\Core\ORM\Entity;
use Espo\Entities\Notification;
use Espo\Entities\User;
use Espo\ORM\EntityManager;
class CollaboratorsNotificator
{
public function __construct(
private Helper $helper,
private EntityManager $entityManager,
private User $user,
private UserEnabledChecker $userEnabledChecker,
) {}
public function process(Entity $entity, Params $params): void
{
if (!$this->toProcess($entity)) {
return;
}
$userIds = $entity->getLinkMultipleIdList(Field::COLLABORATORS);
$previousUserIds = $entity->getFetchedLinkMultipleIdList(Field::COLLABORATORS);
$addedUserIds = array_diff($userIds, $previousUserIds);
foreach ($addedUserIds as $userId) {
$this->processForUser($entity, $userId, $params);
}
}
private function processForUser(Entity $entity, string $userId, Params $params): void
{
if (!$this->toProcessUser($entity, $userId)) {
return;
}
$notification = $this->entityManager->getRDBRepositoryByClass(Notification::class)->getNew();
$notification
->setType(Notification::TYPE_COLLABORATING)
->setUserId($userId)
->setData([
'relatedName' => $entity->get(Field::NAME),
'createdByName' => $this->user->getName(),
])
->setRelated(LinkParent::fromEntity($entity))
// Needed for grouping.
->setRelatedParent(LinkParent::fromEntity($entity))
->setActionId($params->getActionId());
$this->entityManager->saveEntity($notification);
}
private function toProcessUser(Entity $entity, string $userId): bool
{
$entityType = $entity->getEntityType();
if ($userId === $this->user->getId()) {
return false;
}
if ($this->helper->hasAssignedUsersField($entityType)) {
return !in_array($userId, $entity->getLinkMultipleIdList(Field::ASSIGNED_USERS));
}
if ($this->helper->hasAssignedUserField($entityType)) {
return $userId !== $entity->get(Field::ASSIGNED_USER . 'Id');
}
if (!$this->userEnabledChecker->checkAssignment($entityType, $userId)) {
return false;
}
return true;
}
private function toProcess(Entity $entity): bool
{
if (!$this->helper->hasCollaboratorsField($entity->getEntityType())) {
return false;
}
$idsAttr = Field::COLLABORATORS . 'Ids';
if (!$entity->isAttributeChanged($idsAttr)) {
return false;
}
return true;
}
}

View File

@@ -0,0 +1,434 @@
<?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\Notification;
use Espo\Core\Acl;
use Espo\Core\Exceptions\BadRequest;
use Espo\Core\Exceptions\Forbidden;
use Espo\Core\Record\Collection as RecordCollection;
use Espo\Core\Select\SearchParams;
use Espo\Core\Select\SelectBuilderFactory;
use Espo\Entities\Notification;
use Espo\Entities\User;
use Espo\ORM\Collection;
use Espo\ORM\EntityManager;
use Espo\ORM\Name\Attribute;
use Espo\ORM\Query\DeleteBuilder;
use Espo\ORM\Query\Part\Condition as Cond;
use Espo\ORM\Query\Part\Expression as Expr;
use Espo\ORM\Query\Select;
use Espo\ORM\Query\SelectBuilder;
use Espo\ORM\Query\UpdateBuilder;
class GroupAllService
{
public function __construct(
private EntityManager $entityManager,
private Acl $acl,
private User $user,
private RecordService $recordService,
private SelectBuilderFactory $selectBuilderFactory,
) {}
/**
* @return RecordCollection<Notification>
* @throws BadRequest
* @throws Forbidden
*/
public function get(string $type, string $groupId, SearchParams $searchParams): RecordCollection
{
$searchParams = $this->amendMaxSize($type, $groupId, $searchParams);
$recordCollection = $this->getInternal($type, $groupId, $searchParams);
$recordCollection = $this->prepareRecordCollection($recordCollection);
$this->markAsRead($recordCollection);
return $recordCollection;
}
/**
* @return RecordCollection<Notification>
* @throws BadRequest
* @throws Forbidden
*/
private function getInternal(string $type, string $groupId, SearchParams $searchParams): RecordCollection
{
$collection = null;
if ($type == Notification::GROUP_TYPE_RECORD) {
$collection = $this->getNote($groupId, $searchParams);
} else if ($type == Notification::GROUP_TYPE_EMAIL_RECEIVED) {
$collection = $this->getEmailReceived($searchParams);
}
if (!$collection) {
throw new BadRequest("Bad group.");
}
return $collection;
}
/**
* @return RecordCollection<Notification>
* @throws BadRequest
* @throws Forbidden
*/
private function getNote(string $groupId, SearchParams $searchParams): RecordCollection
{
if (substr_count($groupId, '_') < 2) {
throw new BadRequest("Bad ID.");
}
[, $entityType, $id] = explode('_', $groupId, 3);
if (!$this->acl->checkScope($entityType)) {
/** @var Collection<Notification> $collection */
$collection = $this->entityManager->getCollectionFactory()->create(Notification::ENTITY_TYPE);
return RecordCollection::create($collection, 0);
}
$maxSize = $searchParams->getMaxSize();
if ($maxSize) {
$searchParams = $searchParams->withMaxSize($maxSize + 1);
}
$builder = $this->prepareBuilder($searchParams);
$query = $builder
->where([
Notification::FIELD_TYPE => $this->recordService->getRecordGroupNoteTypes(),
Notification::ATTR_RELATED_PARENT_TYPE => $entityType,
Notification::ATTR_RELATED_PARENT_ID => $id,
])
->build();
$collection = $this->runQuery($query);
return RecordCollection::createNoCount($collection, $maxSize);
}
/**
* @return RecordCollection<Notification>
* @throws BadRequest
* @throws Forbidden
*/
private function getEmailReceived(SearchParams $searchParams): RecordCollection
{
$maxSize = $searchParams->getMaxSize();
if ($maxSize) {
$searchParams = $searchParams->withMaxSize($maxSize + 1);
}
$builder = $this->prepareBuilder($searchParams);
$query = $builder
->where([
Notification::FIELD_TYPE => Notification::TYPE_EMAIL_RECEIVED,
])
->build();
$collection = $this->runQuery($query);
return RecordCollection::createNoCount($collection, $maxSize);
}
/**
* @return Collection<Notification>
*/
private function runQuery(Select $query): Collection
{
return$this->entityManager
->getRDBRepositoryByClass(Notification::class)
->clone($query)
->find();
}
/**
* @throws BadRequest
*/
public function markRead(string $groupId): void
{
if (substr_count($groupId, '_') < 1) {
throw new BadRequest("Bad ID.");
}
[$type,] = explode('_', $groupId, 2);
if ($type == Notification::GROUP_TYPE_RECORD) {
$this->markReadNote($groupId);
return;
}
if ($type == Notification::GROUP_TYPE_EMAIL_RECEIVED) {
$this->markReadEmailReceived();
return;
}
throw new BadRequest("Bad group type.");
}
/**
* @param string[] $ids
*/
private function markAsReadByIds(array $ids): void
{
if ($ids === []) {
return;
}
$query = $this->entityManager
->getQueryBuilder()
->update()
->in(Notification::ENTITY_TYPE)
->set([Notification::ATTR_READ => true])
->where([Notification::ATTR_USER_ID => $this->user->getId()])
->where(
Cond::in(Expr::column(Attribute::ID), $ids)
)
->build();
$this->entityManager->getQueryExecutor()->execute($query);
}
/**
* @param RecordCollection<Notification> $collection
*/
private function markAsRead(RecordCollection $collection): void
{
$ids = [];
foreach ($collection->getCollection() as $entity) {
$ids[] = $entity->getId();
}
$this->markAsReadByIds($ids);
}
/**
* @return SelectBuilder
* @throws BadRequest
* @throws Forbidden
*/
private function prepareBuilder(SearchParams $searchParams): SelectBuilder
{
return $this->selectBuilderFactory
->create()
->from(Notification::ENTITY_TYPE)
->withSearchParams($searchParams)
->withComplexExpressionsForbidden()
->buildQueryBuilder()
->where([
Notification::ATTR_USER_ID => $this->user->getId(),
]);
}
/**
* @throws BadRequest
*/
public function remove(string $groupId): void
{
if (substr_count($groupId, '_') < 1) {
throw new BadRequest("Bad ID.");
}
[$type,] = explode('_', $groupId, 2);
if ($type == Notification::GROUP_TYPE_RECORD) {
$this->removeNote($groupId);
return;
}
if ($type == Notification::GROUP_TYPE_EMAIL_RECEIVED) {
$this->removeEmailReceived();
return;
}
throw new BadRequest("Bad group type.");
}
/**
* @throws BadRequest
*/
private function removeNote(string $groupId): void
{
if (substr_count($groupId, '_') < 2) {
throw new BadRequest("Bad ID.");
}
[, $entityType, $id] = explode('_', $groupId, 3);
$query = DeleteBuilder::create()
->from(Notification::ENTITY_TYPE)
->where([
Notification::ATTR_USER_ID => $this->user->getId(),
])
->where([
Notification::FIELD_TYPE => $this->recordService->getRecordGroupNoteTypes(),
Notification::ATTR_RELATED_PARENT_TYPE => $entityType,
Notification::ATTR_RELATED_PARENT_ID => $id,
])
->build();
$this->entityManager->getQueryExecutor()->execute($query);
}
private function removeEmailReceived(): void
{
$query = DeleteBuilder::create()
->from(Notification::ENTITY_TYPE)
->where([
Notification::ATTR_USER_ID => $this->user->getId(),
])
->where([
Notification::FIELD_TYPE => Notification::TYPE_EMAIL_RECEIVED,
])
->build();
$this->entityManager->getQueryExecutor()->execute($query);
}
/**
* @throws BadRequest
*/
private function markReadNote(string $groupId): void
{
if (substr_count($groupId, '_') < 2) {
throw new BadRequest("Bad ID.");
}
[, $entityType, $id] = explode('_', $groupId, 3);
$query = UpdateBuilder::create()
->in(Notification::ENTITY_TYPE)
->where([
Notification::ATTR_USER_ID => $this->user->getId(),
])
->where([
Notification::FIELD_TYPE => $this->recordService->getRecordGroupNoteTypes(),
Notification::ATTR_RELATED_PARENT_TYPE => $entityType,
Notification::ATTR_RELATED_PARENT_ID => $id,
Notification::ATTR_READ => false,
])
->set([
Notification::ATTR_READ => true,
])
->build();
$this->entityManager->getQueryExecutor()->execute($query);
}
private function markReadEmailReceived(): void
{
$query = UpdateBuilder::create()
->in(Notification::ENTITY_TYPE)
->where([
Notification::ATTR_USER_ID => $this->user->getId(),
])
->where([
Notification::FIELD_TYPE => Notification::TYPE_EMAIL_RECEIVED,
Notification::ATTR_READ => false,
])
->set([
Notification::ATTR_READ => true,
])
->build();
$this->entityManager->getQueryExecutor()->execute($query);
}
private function hasBeforeNumber(SearchParams $searchParams): bool
{
foreach ($searchParams->getWhere()?->getItemList() ?? [] as $item) {
if ($item->getAttribute() === Notification::ATTR_NUMBER) {
return true;
}
}
return false;
}
/**
* @throws BadRequest
* @throws Forbidden
*/
private function amendMaxSize(string $type, string $groupId, SearchParams $searchParams): SearchParams
{
if ($this->hasBeforeNumber($searchParams)) {
return $searchParams;
}
$collection = $this->getInternal($type, $groupId, $searchParams);
$firstReadIndex = -1;
$hasNotRead = false;
$hasNotReadAfterRead = false;
foreach ($collection->getCollection() as $i => $entity) {
if ($entity->isRead() && $firstReadIndex === -1) {
$firstReadIndex = $i;
}
if (!$entity->isRead()) {
$hasNotRead = true;
}
if ($firstReadIndex !== -1 && !$entity->isRead()) {
$hasNotReadAfterRead = true;
}
}
if ($firstReadIndex !== -1 && $hasNotRead && !$hasNotReadAfterRead) {
$searchParams = $searchParams->withMaxSize($firstReadIndex);
}
return $searchParams;
}
/**
* @param RecordCollection<Notification> $recordCollection
* @return RecordCollection<Notification>
*/
private function prepareRecordCollection(RecordCollection $recordCollection): RecordCollection
{
$collection = $recordCollection->getCollection();
$collection = $this->recordService->prepareCollection($collection, $this->user);
return new RecordCollection($collection, $recordCollection->getTotal());
}
}

View File

@@ -0,0 +1,76 @@
<?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\Notification;
use Espo\Core\Record\Collection as RecordCollection;
use Espo\Entities\Notification;
use Espo\Entities\User;
use Espo\ORM\Collection;
use Espo\ORM\EntityManager;
use Espo\ORM\Name\Attribute;
class GroupService
{
private const LIMIT = 100;
public function __construct(
private EntityManager $entityManager,
private User $user,
private RecordService $recordService,
) {}
/**
* @return RecordCollection<Notification>
*/
public function get(Notification $notification): RecordCollection
{
if (!$notification->getActionId()) {
/** @var Collection<Notification> $collection */
$collection = $this->entityManager->getCollectionFactory()->create(Notification::ENTITY_TYPE);
return RecordCollection::create($collection, 0);
}
$collection = $this->entityManager
->getRDBRepositoryByClass(Notification::class)
->where([
Attribute::ID . '!=' => $notification->getId(),
Notification::ATTR_ACTION_ID => $notification->getActionId(),
Notification::ATTR_USER_ID => $this->user->getId(),
])
->limit(0, self::LIMIT)
->order(Notification::ATTR_NUMBER)
->find();
$collection = $this->recordService->prepareCollection($collection, $this->user);
return RecordCollection::create($collection, count($collection));
}
}

View File

@@ -0,0 +1,260 @@
<?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\Notification;
use Espo\Core\Name\Field;
use Espo\Core\Notification\AssignmentNotificatorFactory;
use Espo\Core\Notification\AssignmentNotificator;
use Espo\Core\Notification\AssignmentNotificator\Params as AssignmentNotificatorParams;
use Espo\ORM\Repository\Option\SaveContext;
use Espo\Core\Utils\Metadata;
use Espo\Core\Utils\Config;
use Espo\Tools\Stream\Service as StreamService;
use Espo\ORM\EntityManager;
use Espo\ORM\Entity;
use Espo\Entities\User;
use Espo\Entities\Notification;
use Espo\Core\ORM\Entity as CoreEntity;
/**
* Handles operations with entities.
*/
class HookProcessor
{
/** @var array<string, AssignmentNotificator<Entity>> */
private $notificatorsHash = [];
/** @var array<string, bool> */
private $hasStreamCache = [];
/** @var array<string, string> */
private $userNameHash = [];
public function __construct(
private Metadata $metadata,
private Config $config,
private EntityManager $entityManager,
private StreamService $streamService,
private AssignmentNotificatorFactory $notificatorFactory,
private User $user,
private CollaboratorsNotificator $collaboratorsNotificator,
) {}
/**
* @param array<string, mixed> $options
*/
public function afterSave(Entity $entity, array $options): void
{
if (!$entity instanceof CoreEntity) {
return;
}
$this->processAssignment($entity, $options);
$this->processCollaborating($entity, $options);
}
/**
* @param array<string, mixed> $options
*/
private function processAssignment(CoreEntity $entity, array $options): void
{
$entityType = $entity->getEntityType();
$hasStream = $this->checkHasStream($entityType);
$force = $this->forceAssignmentNotificator($entityType);
/**
* No need to process assignment notifications for entity types that have Stream enabled.
* Users are notified via Stream notifications.
*/
if ($hasStream && !$force) {
return;
}
if (
(!$force || !$hasStream) &&
!in_array($entityType, $this->getAssignmentEnabledEntityTypeList())
) {
return;
}
$notificator = $this->getNotificator($entityType);
$params = $this->createParams($options);
$notificator->process($entity, $params);
}
/**
* @param array<string, mixed> $options
*/
public function beforeRemove(Entity $entity, array $options): void
{
$entityType = $entity->getEntityType();
if (!$this->checkHasStream($entityType)) {
return;
}
$followersData = $this->streamService->getEntityFollowers($entity);
$userIdList = $followersData['idList'];
$removedById = $options['modifiedById'] ?? $this->user->getId();
$removedByName = $this->getUserNameById($removedById);
foreach ($userIdList as $userId) {
if ($userId === $removedById) {
continue;
}
$this->entityManager->createEntity(Notification::ENTITY_TYPE, [
'userId' => $userId,
'type' => Notification::TYPE_ENTITY_REMOVED,
'data' => [
'entityType' => $entity->getEntityType(),
'entityId' => $entity->getId(),
'entityName' => $entity->get(Field::NAME),
'userId' => $removedById,
'userName' => $removedByName,
],
]);
}
}
public function afterRemove(Entity $entity): void
{
$query = $this->entityManager
->getQueryBuilder()
->delete()
->from(Notification::ENTITY_TYPE)
->where([
'OR' => [
[
'relatedId' => $entity->getId(),
'relatedType' => $entity->getEntityType(),
],
[
'relatedParentId' => $entity->getId(),
'relatedParentType' => $entity->getEntityType(),
],
],
])
->build();
$this->entityManager->getQueryExecutor()->execute($query);
}
private function checkHasStream(string $entityType): bool
{
if (!array_key_exists($entityType, $this->hasStreamCache)) {
$this->hasStreamCache[$entityType] =
(bool) $this->metadata->get(['scopes', $entityType, 'stream']);
}
return $this->hasStreamCache[$entityType];
}
/**
* @return AssignmentNotificator<Entity>
*/
private function getNotificator(string $entityType): AssignmentNotificator
{
if (empty($this->notificatorsHash[$entityType])) {
$notificator = $this->notificatorFactory->create($entityType);
$this->notificatorsHash[$entityType] = $notificator;
}
return $this->notificatorsHash[$entityType];
}
private function getUserNameById(string $id): string
{
if ($id === $this->user->getId()) {
return $this->user->get(Field::NAME);
}
if (!array_key_exists($id, $this->userNameHash)) {
/** @var ?User $user */
$user = $this->entityManager->getEntityById(User::ENTITY_TYPE, $id);
if ($user) {
$this->userNameHash[$id] = $user->getName() ?? $id;
}
}
return $this->userNameHash[$id];
}
private function forceAssignmentNotificator(string $entityType): bool
{
return (bool) $this->metadata->get(['notificationDefs', $entityType, 'forceAssignmentNotificator']);
}
/**
* @param array<string, mixed> $options
*/
private function createParams(array $options): AssignmentNotificatorParams
{
$params = AssignmentNotificatorParams::create()->withRawOptions($options);
$saveContext = SaveContext::obtainFromRawOptions($options);
if ($saveContext) {
$params = $params->withActionId($saveContext->getActionId());
}
return $params;
}
/**
* @return string[]
*/
private function getAssignmentEnabledEntityTypeList(): array
{
return $this->config->get('assignmentNotificationsEntityList') ?? [];
}
/**
* @param array<string, mixed> $options
*/
private function processCollaborating(CoreEntity $entity, array $options): void
{
// If stream is enabled, then always process. Otherwise, use the parameter for 'assignment'.
if (
!$this->checkHasStream($entity->getEntityType()) &&
!in_array($entity->getEntityType(), $this->getAssignmentEnabledEntityTypeList())
) {
return;
}
$this->collaboratorsNotificator->process($entity, $this->createParams($options));
}
}

View File

@@ -0,0 +1,37 @@
<?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\Notification\HookProcessor;
readonly class Params
{
public function __construct(
public ?string $actionId = null,
) {}
}

View File

@@ -0,0 +1,435 @@
<?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\Notification;
use Espo\Core\AclManager as InternalAclManager;
use Espo\Core\Acl\Table;
use Espo\Core\Name\Field;
use Espo\ORM\Name\Attribute;
use Espo\Tools\Notification\HookProcessor\Params;
use Espo\Tools\Stream\Service as StreamService;
use Espo\ORM\EntityManager;
use Espo\ORM\SthCollection;
use Espo\ORM\EntityCollection;
use Espo\Entities\User;
use Espo\Entities\Team;
use Espo\Entities\Portal;
use Espo\Entities\Notification;
use Espo\Entities\Note;
/**
* Handles notifications after note saving.
*/
class NoteHookProcessor
{
public function __construct(
private StreamService $streamService,
private Service $service,
private EntityManager $entityManager,
private User $user,
private InternalAclManager $internalAclManager
) {}
public function afterSave(Note $note, Params $params): void
{
if ($note->getParentType() && $note->getParentId()) {
$this->afterSaveParent($note, $params);
return;
}
$this->afterSaveNoParent($note);
}
private function afterSaveParent(Note $note, Params $params): void
{
$parentType = $note->getParentType();
$parentId = $note->getParentId();
$superParentType = $note->getSuperParentType();
$superParentId = $note->getSuperParentId();
if (!$parentType || !$parentId) {
return;
}
$users = $this->getSubscriberList($parentType, $parentId, $note->isInternal());
$regularUserIds = [];
foreach ($users as $user) {
$regularUserIds[] = $user->getId();
}
$superUserIds = [];
if ($superParentType && $superParentId) {
$superUsers = $this->getSubscriberList($superParentType, $superParentId, $note->isInternal());
$superUsers = $superUsers->filter(function (User $user) use ($regularUserIds) {
return !$user->isPortal() && !in_array($user->getId(), $regularUserIds);
});
foreach ($superUsers as $user) {
$superUserIds[] = $user->getId();
$users[] = $user;
}
}
$targetType = $note->getRelatedType() ? $note->getRelatedType() : $parentType;
// This is correct.
$skipAclCheck = !$note->isAclProcessed();
$teamIdList = null;
$regularUserIds = null;
if (!$skipAclCheck) {
$teamIdList = $note->getLinkMultipleIdList(Field::TEAMS);
$regularUserIds = $note->getLinkMultipleIdList('users');
}
$notifyUserIdList = [];
foreach ($users as $user) {
if ($skipAclCheck) {
$notifyUserIdList[] = $user->getId();
continue;
}
/** @var string[] $regularUserIds */
/** @var string[] $teamIdList */
if ($user->isAdmin()) {
$notifyUserIdList[] = $user->getId();
continue;
}
if ($user->isPortal() && $note->getRelatedType()) {
continue;
}
if ($user->isPortal()) {
$notifyUserIdList[] = $user->getId();
continue;
}
$level = $this->internalAclManager->getLevel($user, $targetType, Table::ACTION_READ);
if (!$this->checkUserAccess($user, $level, $teamIdList, $regularUserIds)) {
continue;
}
$notifyUserIdList[] = $user->getId();
}
$regularIds = array_unique(array_diff($notifyUserIdList, $superUserIds));
$superIds = array_unique(array_intersect($notifyUserIdList, $superUserIds));
$this->processNotify($note, $regularIds, $params);
$this->processNotify($note, $superIds, $params, true);
}
private function afterSaveNoParent(Note $note): void
{
$targetType = $note->getTargetType();
if ($targetType === Note::TARGET_USERS) {
$this->afterSaveTargetUsers($note);
return;
}
if ($targetType === Note::TARGET_TEAMS) {
$this->afterSaveTargetTeams($note);
return;
}
if ($targetType === Note::TARGET_PORTALS) {
$this->afterSaveTargetPortals($note);
return;
}
if ($targetType === Note::TARGET_ALL) {
$this->afterSaveTargetAll($note);
}
}
/**
* @param string[] $userIdList
*/
private function processNotify(Note $note, array $userIdList, ?Params $params = null, bool $isSuper = false): void
{
$filteredUserIdList = array_filter(
$userIdList,
function (string $userId) use ($note) {
if ($note->isUserIdNotified($userId)) {
return false;
}
if ($note->isNew()) {
return true;
}
$existing = $this->entityManager
->getRDBRepository(Notification::ENTITY_TYPE)
->select([Attribute::ID])
->where([
'type' => Notification::TYPE_NOTE,
'relatedType' => Note::ENTITY_TYPE,
'relatedId' => $note->getId(),
'userId' => $userId,
])
->findOne();
if ($existing) {
return false;
}
return true;
}
);
if (!count($filteredUserIdList)) {
return;
}
$notifyParams = new NoteNotifyParams(isSuper: $isSuper);
$this->service->notifyAboutNote(
userIdList: $filteredUserIdList,
note: $note,
params: $params,
notifyParams: $notifyParams,
);
}
private function afterSaveTargetUsers(Note $note): void
{
$targetUserIdList = $note->get('usersIds') ?? [];
if (!count($targetUserIdList)) {
return;
}
$notifyUserIdList = [];
foreach ($targetUserIdList as $userId) {
if ($userId === $this->user->getId()) {
continue;
}
$notifyUserIdList[] = $userId;
}
$this->processNotify($note, array_unique($notifyUserIdList));
}
private function afterSaveTargetTeams(Note $note): void
{
$targetTeamIdList = $note->get('teamsIds') ?? [];
if (!count($targetTeamIdList)) {
return;
}
$notifyUserIdList = [];
foreach ($targetTeamIdList as $teamId) {
$team = $this->entityManager->getEntityById(Team::ENTITY_TYPE, $teamId);
if (!$team) {
continue;
}
$targetUserList = $this->entityManager
->getRDBRepository(Team::ENTITY_TYPE)
->getRelation($team, 'users')
->where([
'isActive' => true,
])
->select(Attribute::ID)
->find();
foreach ($targetUserList as $user) {
if ($user->getId() === $this->user->getId()) {
continue;
}
$notifyUserIdList[] = $user->getId();
}
}
$this->processNotify($note, array_unique($notifyUserIdList));
}
private function afterSaveTargetPortals(Note $note): void
{
$targetPortalIdList = $note->get('portalsIds') ?? [];
if (!count($targetPortalIdList)) {
return;
}
$notifyUserIdList = [];
foreach ($targetPortalIdList as $portalId) {
$portal = $this->entityManager->getEntityById(Portal::ENTITY_TYPE, $portalId);
if (!$portal) {
continue;
}
$targetUserList = $this->entityManager
->getRDBRepository(Portal::ENTITY_TYPE)
->getRelation($portal, 'users')
->where([
'isActive' => true,
])
->select([Attribute::ID])
->find();
foreach ($targetUserList as $user) {
if ($user->getId() === $this->user->getId()) {
continue;
}
$notifyUserIdList[] = $user->getId();
}
}
$this->processNotify($note, array_unique($notifyUserIdList));
}
private function afterSaveTargetAll(Note $note): void
{
$targetUserList = $this->entityManager
->getRDBRepository(User::ENTITY_TYPE)
->where([
'isActive' => true,
'type' => ['regular', 'admin'],
])
->select(Attribute::ID)
->find();
$notifyUserIdList = [];
foreach ($targetUserList as $user) {
if ($user->getId() === $this->user->getId()) {
continue;
}
$notifyUserIdList[] = $user->getId();
}
$this->processNotify($note, $notifyUserIdList);
}
/**
* @param string[] $teamIdList
* @param string[] $userIdList
* @return bool
*/
private function checkUserAccess(
User $user,
string $level,
array $teamIdList,
array $userIdList
): bool {
if ($level === Table::LEVEL_ALL) {
return true;
}
if ($level === Table::LEVEL_TEAM) {
if (in_array($user->getId(), $userIdList)) {
return true;
}
if (!count($teamIdList)) {
return false;
}
$userTeamIdList = $user->getLinkMultipleIdList(Field::TEAMS);
foreach ($teamIdList as $teamId) {
if (in_array($teamId, $userTeamIdList)) {
return true;
}
}
return false;
}
if ($level === Table::LEVEL_OWN) {
return in_array($user->getId(), $userIdList);
}
return false;
}
/**
* @return EntityCollection<User>
*/
private function getSubscriberList(string $parentType, string $parentId, bool $isInternal = false): EntityCollection
{
$collection = $this->streamService->getSubscriberList($parentType, $parentId, $isInternal);
if ($collection instanceof EntityCollection) {
return $collection;
}
if ($collection instanceof SthCollection) {
/** @var EntityCollection<User> */
return $this->entityManager
->getCollectionFactory()
->createFromSthCollection($collection);
}
/** @var EntityCollection<User> $newCollection */
$newCollection = $this->entityManager
->getCollectionFactory()
->create(User::ENTITY_TYPE);
foreach ($collection as $entity) {
$newCollection[] = $entity;
}
return $newCollection;
}
}

View File

@@ -0,0 +1,159 @@
<?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\Notification;
use Espo\Core\Acl;
use Espo\Core\Acl\Permission;
use Espo\Core\AclManager;
use Espo\ORM\EntityManager;
use Espo\Entities\User;
use Espo\Entities\Note;
use stdClass;
class NoteMentionHookProcessor
{
public function __construct(
private Service $service,
private EntityManager $entityManager,
private User $user,
private Acl $acl,
private AclManager $aclManager
) {}
public function beforeSave(Note $note): void
{
if ($note->getType() !== Note::TYPE_POST) {
return;
}
$this->process($note);
}
private function process(Note $note): void
{
$mentionData = (object) [];
$previousMentionList = [];
if (!$note->isNew()) {
$previousMentionList = array_keys(get_object_vars($note->getData()->mentions ?? (object) []));
}
$matches = null;
preg_match_all('/(@[\w@.-]+)/', $note->getPost() ?? '', $matches);
$mentionCount = 0;
if (!empty($matches[0]) && is_array($matches[0])) {
$mentionCount = $this->processMatches($matches[0], $note, $mentionData, $previousMentionList);
}
$data = $note->getData();
if ($mentionCount) {
$data->mentions = $mentionData;
} else {
unset($data->mentions);
}
$note->setData($data);
}
/**
* @param string[] $matchList
* @param string[] $previousMentionList
*/
private function processMatches(
array $matchList,
Note $note,
stdClass $mentionData,
array $previousMentionList
): int {
$mentionCount = 0;
$parent = $note->getParentId() && $note->getParentType() ?
$this->entityManager->getEntityById($note->getParentType(), $note->getParentId()) :
null;
foreach ($matchList as $item) {
$userName = substr($item, 1);
$user = $this->entityManager
->getRDBRepositoryByClass(User::class)
->where([
'userName' => $userName,
'isActive' => true,
])
->findOne();
if (!$user) {
continue;
}
if (!$this->acl->checkUserPermission($user, Permission::MENTION)) {
continue;
}
$mentionData->$item = (object) [
'id' => $user->getId(),
'name' => $user->getName(),
'userName' => $user->getUserName(),
'_scope' => $user->getEntityType(),
];
$mentionCount++;
if (in_array($item, $previousMentionList)) {
continue;
}
if ($user->getId() === $this->user->getId()) {
continue;
}
if ($user->isPortal()) {
continue;
}
if ($parent && !$this->aclManager->checkEntityStream($user, $parent)) {
continue;
}
$note->addNotifiedUserId($user->getId());
$this->service->notifyAboutMentionInPost($user->getId(), $note);
}
return $mentionCount;
}
}

View File

@@ -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\Notification;
/**
* @since 10.0.1
*/
readonly class NoteNotifyParams
{
public function __construct(
public bool $isSuper = false,
) {}
}

View File

@@ -0,0 +1,959 @@
<?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\Notification;
use Espo\Core\Acl;
use Espo\Core\Exceptions\BadRequest;
use Espo\Core\Exceptions\Error;
use Espo\Core\Exceptions\Forbidden;
use Espo\Core\Name\Field;
use Espo\Core\Record\Collection as RecordCollection;
use Espo\Core\Select\SearchParams;
use Espo\Core\Select\SelectBuilderFactory;
use Espo\Core\Utils\Config;
use Espo\Core\Utils\Metadata;
use Espo\Entities\Note;
use Espo\Entities\Notification;
use Espo\Entities\User;
use Espo\ORM\Collection;
use Espo\ORM\EntityCollection;
use Espo\ORM\EntityManager;
use Espo\ORM\Name\Attribute;
use Espo\ORM\Query\Part\Condition as Cond;
use Espo\ORM\Query\Part\Expression as Expr;
use Espo\ORM\Query\Part\Order;
use Espo\ORM\Query\Part\Selection;
use Espo\ORM\Query\Part\WhereItem;
use Espo\ORM\Query\SelectBuilder;
use Espo\ORM\Query\Union;
use Espo\ORM\Query\UnionBuilder;
use Espo\ORM\Repository\RDBSelectBuilder;
use Espo\Tools\Stream\NoteAccessControl;
use Espo\Tools\User\PreferencesProvider;
use PDO;
use UnexpectedValueException;
class RecordService
{
private const string COLUMN_GROUP_TYPE = 'groupType';
private const string COLUMN_GROUP_UNREAD_COUNT = 'groupedUnreadCount';
/** @var string[] */
private array $noGroupAttributes = [
Attribute::DELETED,
Field::CREATED_BY . 'Id',
Notification::ATTR_ACTION_ID,
Notification::FIELD_DATA,
Notification::FIELD_MESSAGE,
Notification::FIELD_TYPE,
Notification::ATTR_RELATED_ID,
Notification::ATTR_RELATED_TYPE,
];
public function __construct(
private EntityManager $entityManager,
private Acl $acl,
private Metadata $metadata,
private NoteAccessControl $noteAccessControl,
private SelectBuilderFactory $selectBuilderFactory,
private Config $config,
private PreferencesProvider $preferencesProvider,
) {}
/**
* Get notifications for a user.
*
* @return RecordCollection<Notification>
* @throws Error
* @throws BadRequest
* @throws Forbidden
*
* @internal
*/
public function get(User $user, SearchParams $searchParams, ?string $beforeNumber = null): RecordCollection
{
$queryBuilder = $this->isGroupingEnabled($user) ?
$this->prepareGroupingQueryBuilder($user, $searchParams, beforeNumber: $beforeNumber) :
$this->prepareQueryBuilder($user, $searchParams, beforeNumber: $beforeNumber);
$offset = $searchParams->getOffset();
$limit = $searchParams->getMaxSize();
if ($limit) {
$queryBuilder->limit($offset, $limit + 1);
}
$query = $queryBuilder->build();
if ($query instanceof Union) {
$collection = $this->fetchAndPrepareCollectionFromUnion($query);
} else {
$collection = $this->entityManager
->getRDBRepositoryByClass(Notification::class)
->clone($query)
->find();
}
if (!$collection instanceof EntityCollection) {
throw new Error("Collection is not instance of EntityCollection.");
}
$collection = $this->prepareCollection($collection, $user);
$groupedCountMap = $this->getActionGroupedCountMap($collection, $user->getId());
$ids = [];
$actionIds = [];
foreach ($collection as $i => $entity) {
if ($i === $limit) {
break;
}
if (!$entity->getGroupType()) {
$ids[] = $entity->getId();
}
$groupedCount = null;
if ($this->isGroupingEnabled($user) && $entity->getGroupType()) {
$groupedCount = -1;
$entity->loadParentNameField(Notification::FIELD_RELATED_PARENT);
}
if ($entity->getActionId() && $this->isActionGroupingEnabled() && !$this->isGroupingEnabled($user)) {
$actionIds[] = $entity->getActionId();
$groupedCount = $groupedCountMap[$entity->getActionId()] ?? 0;
}
$entity->setGroupedCount($groupedCount);
}
$collection = new EntityCollection([...$collection], Notification::ENTITY_TYPE);
$this->markAsRead($user, $ids, $actionIds);
return RecordCollection::createNoCount($collection, $limit);
}
/**
* @param Collection<Notification> $collection
* @return EntityCollection<Notification>
*/
public function prepareCollection(Collection $collection, User $user): EntityCollection
{
if (!$collection instanceof EntityCollection) {
$collection = new EntityCollection([...$collection], Notification::ENTITY_TYPE);
}
$limit = count($collection);
foreach ($collection as $i => $entity) {
if ($i === $limit) {
break;
}
$this->prepareListItem(
entity: $entity,
index: $i,
collection: $collection,
count: $limit,
user: $user,
);
}
/** @var EntityCollection<Notification> */
return new EntityCollection([...$collection], Notification::ENTITY_TYPE);
}
/**
* @param string[] $ids
* @param string[] $actionIds
*/
private function markAsRead(User $user, array $ids, array $actionIds): void
{
if ($ids === [] && $actionIds === []) {
return;
}
$query = $this->entityManager
->getQueryBuilder()
->update()
->in(Notification::ENTITY_TYPE)
->set([Notification::ATTR_READ => true])
->where([Notification::ATTR_USER_ID => $user->getId()])
->where(
Cond::or(
Cond::in(Expr::column(Attribute::ID), $ids),
Cond::in(Expr::column(Notification::ATTR_ACTION_ID), $actionIds),
)
)
->build();
$this->entityManager->getQueryExecutor()->execute($query);
}
/**
* @param EntityCollection<Notification> $collection
*/
private function prepareListItem(
Notification $entity,
int $index,
EntityCollection $collection,
?int &$count,
User $user
): void {
$this->prepareSetFields($entity);
$noteId = $this->getNoteId($entity);
if (!$noteId) {
return;
}
if (
!in_array($entity->getType(), [
Notification::TYPE_NOTE,
Notification::TYPE_MENTION_IN_POST,
Notification::TYPE_USER_REACTION,
])
) {
return;
}
$note = $this->entityManager->getRDBRepositoryByClass(Note::class)->getById($noteId);
if (!$note) {
unset($collection[$index]);
if ($count !== null) {
$count--;
}
$this->entityManager->removeEntity($entity);
return;
}
$this->noteAccessControl->apply($note, $user);
$this->loadNoteFields($note, $entity);
$entity->set('noteData', $note->getValueMap());
if ($entity->getType() === Notification::TYPE_USER_REACTION) {
$entity->loadParentNameField(Notification::FIELD_RELATED_PARENT);
}
}
/**
* @throws BadRequest
* @throws Forbidden
*/
public function getNotReadCount(User $user): int
{
$searchParams = SearchParams::create();
$queryBuilder = $this->isGroupingEnabled($user) ?
$this->prepareGroupingQueryBuilder($user, $searchParams, true) :
$this->prepareQueryBuilder($user, $searchParams, true);
$countQuery = $this->entityManager->getQueryBuilder()
->select()
->fromQuery($queryBuilder->build(), 'q')
->select('COUNT:(q.id)', 'c')
->build();
$sth = $this->entityManager->getQueryExecutor()->execute($countQuery);
$row = $sth->fetch(PDO::FETCH_ASSOC);
$count = $row['c'] ?? null;
if (is_string($count) && is_numeric($count)) {
$count = (int) $count;
}
if (!is_int($count)) {
throw new UnexpectedValueException();
}
return $count;
}
public function markAllRead(string $userId): bool
{
$update = $this->entityManager
->getQueryBuilder()
->update()
->in(Notification::ENTITY_TYPE)
->set(['read' => true])
->where([
'userId' => $userId,
'read' => false,
])
->build();
$this->entityManager->getQueryExecutor()->execute($update);
return true;
}
/**
* @return string[]
*/
private function getIgnoreScopeList(): array
{
$ignoreScopeList = [];
$scopes = $this->metadata->get('scopes', []);
foreach ($scopes as $scope => $item) {
if (empty($item['entity'])) {
continue;
}
if (empty($item['object'])) {
continue;
}
if (!$this->acl->checkScope($scope)) {
$ignoreScopeList[] = $scope;
}
}
return $ignoreScopeList;
}
private function getNoteId(Notification $entity): ?string
{
$noteId = null;
$data = $entity->getData();
if ($data) {
$noteId = $data->noteId ?? null;
}
if ($entity->getRelated()?->getEntityType() === Note::ENTITY_TYPE) {
$noteId = $entity->getRelated()->getId();
}
return $noteId;
}
private function loadNoteFields(Note $note, Notification $notification): void
{
$parentId = $note->getParentId();
$parentType = $note->getParentType();
if ($parentId && $parentType) {
if ($notification->getType() !== Notification::TYPE_USER_REACTION) {
$note->loadParentNameField(Field::PARENT);
}
} else if (!$note->isGlobal()) {
$targetType = $note->getTargetType();
if (!$targetType || $targetType === Note::TARGET_USERS) {
$note->loadLinkMultipleField('users');
}
if ($targetType !== Note::TARGET_USERS) {
if (!$targetType || $targetType === Note::TARGET_TEAMS) {
$note->loadLinkMultipleField(Field::TEAMS);
} else if ($targetType === Note::TARGET_PORTALS) {
$note->loadLinkMultipleField('portals');
}
}
}
$relatedId = $note->getRelatedId();
$relatedType = $note->getRelatedType();
if ($relatedId && $relatedType && $notification->getType() !== Notification::TYPE_USER_REACTION) {
$note->loadParentNameField(Note::FIELD_RELATED);
}
if ($notification->getType() !== Notification::TYPE_USER_REACTION) {
$note->loadLinkMultipleField('attachments');
}
}
private function getActionIdWhere(string $userId): WhereItem
{
return Cond::or(
Expr::isNull(Expr::column('actionId')),
Cond::and(
Expr::isNotNull(Expr::column('actionId')),
Cond::not(
Cond::exists(
SelectBuilder::create()
->from(Notification::ENTITY_TYPE, 'sub')
->select('id')
->where(
Cond::equal(
Expr::column('sub.actionId'),
Expr::column('notification.actionId')
)
)
->where(
Cond::less(
Expr::column('sub.number'),
Expr::column('notification.number')
)
)
->where([Notification::ATTR_USER_ID => $userId])
->build()
)
)
)
);
}
/**
* @param EntityCollection<Notification> $collection
* @return array<string, int>
*/
private function getActionGroupedCountMap(EntityCollection $collection, string $userId): array
{
if (!$this->isActionGroupingEnabled()) {
return [];
}
$groupedCountMap = [];
$actionIds = [];
foreach ($collection as $note) {
if ($note->getActionId()) {
$actionIds[] = $note->getActionId();
}
}
$countsQuery = SelectBuilder::create()
->from(Notification::ENTITY_TYPE)
->select(Expr::count(Expr::column(Attribute::ID)), 'count')
->select(Expr::column(Notification::ATTR_ACTION_ID))
->where([
Notification::ATTR_ACTION_ID => $actionIds,
Notification::ATTR_USER_ID => $userId,
])
->group(Expr::column(Notification::ATTR_ACTION_ID))
->build();
$rows = $this->entityManager->getQueryExecutor()->execute($countsQuery)->fetchAll();
foreach ($rows as $row) {
$actionId = $row[Notification::ATTR_ACTION_ID] ?? null;
if (!is_string($actionId)) {
continue;
}
$groupedCountMap[$actionId] = $row['count'] ?? 0;
}
return $groupedCountMap;
}
private function isActionGroupingEnabled(): bool
{
// @todo Param in preferences?
return (bool) ($this->config->get('notificationGrouping') ?? true);
}
private function prepareSetFields(Notification $entity): void
{
$relatedName = $entity->getData()->relatedName ?? null;
$createdByName = $entity->getData()->createdByName ?? null;
if ($entity->getRelated() && $relatedName !== null) {
$entity->set('relatedName', $relatedName);
}
if ($entity->getCreatedBy() && $createdByName !== null) {
$entity->set('createdByName', $createdByName);
}
}
private function isGroupingEnabled(User $user): bool
{
return $this->preferencesProvider->tryGet($user->getId())?->get('notificationGrouping') ?? false;
}
/**
* @throws BadRequest
* @throws Forbidden
*/
private function prepareGroupingQueryBuilder(
User $user,
SearchParams $searchParams,
bool $notRead = false,
?string $beforeNumber = null,
): UnionBuilder {
$noteGroupBuilder = $this->prepareNoteGroupBuilder(
searchParams: $searchParams,
user: $user,
notRead: $notRead,
beforeNumber: $beforeNumber,
);
$emailGroupBuilder = $this->prepareEmailGroupBuilder(
searchParams: $searchParams,
user: $user,
notRead: $notRead,
beforeNumber: $beforeNumber,
);
$restBuilder = $this->prepareRestBuilder(
searchParams: $searchParams,
user: $user,
notRead: $notRead,
beforeNumber: $beforeNumber,
);
return UnionBuilder::create()
->query($noteGroupBuilder->build())
->query($emailGroupBuilder->build())
->query($restBuilder->build())
->order(Notification::ATTR_NUMBER, Order::DESC);
}
/**
* @param RDBSelectBuilder<Notification>|SelectBuilder $builder
*/
private function applyRelatedAccess(RDBSelectBuilder|SelectBuilder $builder): void
{
$ignoreScopeList = $this->getIgnoreScopeList();
if ($ignoreScopeList === []) {
return;
}
$builder->where([
'OR' => [
Notification::ATTR_RELATED_PARENT_TYPE => null,
Notification::ATTR_RELATED_PARENT_TYPE . '!=' => $ignoreScopeList,
],
]);
}
/**
* @return EntityCollection<Notification>
*/
private function fetchAndPrepareCollectionFromUnion(Union $query): EntityCollection
{
$sth = $this->entityManager->getQueryExecutor()->execute($query);
/** @var EntityCollection<Notification> $collection */
$collection = $this->entityManager->getCollectionFactory()->create(Notification::ENTITY_TYPE);
while ($row = $sth->fetch(PDO::FETCH_ASSOC)) {
$entity = $this->entityManager->getRDBRepositoryByClass(Notification::class)->getNew();
$entity->setMultiple($row);
$entity->setAsFetched();
$collection[] = $entity;
}
return $collection;
}
/**
* @return Selection[]
*/
private function getNullNoGroupSelections(): array
{
return array_map(function ($attribute) {
$raw = null;
if ($attribute === Attribute::DELETED) {
$raw = false;
}
return Selection::create(Expr::value($raw), $attribute);
}, $this->noGroupAttributes);
}
/**
* @throws BadRequest
* @throws Forbidden
*/
private function prepareQueryBuilder(
User $user,
SearchParams $searchParams,
bool $notRead = false,
?string $beforeNumber = null,
): SelectBuilder {
$builder = $this->selectBuilderFactory
->create()
->from(Notification::ENTITY_TYPE)
->withSearchParams($searchParams)
->buildQueryBuilder()
->where([Notification::ATTR_USER_ID => $user->getId()])
->order(Notification::ATTR_NUMBER, SearchParams::ORDER_DESC);
if ($notRead) {
$builder->where([Notification::ATTR_READ => false]);
}
if ($beforeNumber) {
$builder->where([Notification::ATTR_NUMBER . '<' => $beforeNumber]);
}
$this->applyRelatedAccess($builder);
if ($this->isActionGroupingEnabled()) {
$builder->where($this->getActionIdWhere($user->getId()));
}
return $builder;
}
/**
* @throws BadRequest
* @throws Forbidden
*/
private function prepareNoteGroupBuilder(
SearchParams $searchParams,
User $user,
bool $notRead,
?string $beforeNumber,
): SelectBuilder {
if ($searchParams->getMaxSize() !== null) {
$searchParams = $searchParams->withMaxSize($searchParams->getMaxSize() + 1);
}
$builder = $this->selectBuilderFactory
->create()
->from(Notification::ENTITY_TYPE)
->withSearchParams($searchParams)
->buildQueryBuilder()
->select([
Selection::create(
Expr::value(Notification::GROUP_TYPE_RECORD),
self::COLUMN_GROUP_TYPE
),
Selection::create(
Expr::concat(
Expr::value(Notification::GROUP_TYPE_RECORD),
Expr::value('_'),
Expr::column(Notification::ATTR_RELATED_PARENT_TYPE),
Expr::value('_'),
Expr::column(Notification::ATTR_RELATED_PARENT_ID),
),
Attribute::ID
),
Selection::create(
$this->getMaxNumberExpr(),
Notification::ATTR_NUMBER
),
Notification::ATTR_RELATED_PARENT_ID,
Notification::ATTR_RELATED_PARENT_TYPE,
Selection::create(
Expr::switch(
Expr::greater(
Expr::sum(
Expr::switch(
Expr::column(Notification::ATTR_READ),
Expr::value(0),
Expr::value(1),
),
),
0
),
Expr::value(false),
Expr::value(true),
),
Notification::ATTR_READ
),
Selection::create(
Expr::sum(
Expr::switch(
Expr::column(Notification::ATTR_READ),
Expr::value(0),
Expr::value(1),
),
),
self::COLUMN_GROUP_UNREAD_COUNT
),
Selection::create(
Expr::max(Expr::column(Field::CREATED_AT)),
Field::CREATED_AT,
),
Selection::create(
Expr::switch(
Expr::greater(
Expr::sum(
Expr::switch(
Expr::and(
Expr::not(Expr::column(Notification::ATTR_READ)),
Expr::column(Notification::FIELD_IS_FEATURED),
),
Expr::value(1),
Expr::value(0),
),
),
0
),
true,
false,
),
Notification::FIELD_IS_FEATURED
),
...$this->getNullNoGroupSelections(),
])
->where([
Notification::ATTR_RELATED_PARENT_ID . '!=' => null,
Notification::FIELD_TYPE => $this->getRecordGroupNoteTypes(),
])
->where([Notification::ATTR_USER_ID => $user->getId()])
->group(Notification::ATTR_RELATED_PARENT_ID)
->group(Notification::ATTR_RELATED_PARENT_TYPE)
->order([])
->order($this->getMaxNumberExpr(), Order::DESC);
if ($beforeNumber) {
$builder->having(
Cond::less(
$this->getMaxNumberExpr(),
Expr::value($beforeNumber)
)
);
}
$this->applyRelatedAccess($builder);
if ($notRead) {
$builder->where([Notification::ATTR_READ => false]);
}
return $builder;
}
/**
* @throws BadRequest
* @throws Forbidden
*/
private function prepareEmailGroupBuilder(
SearchParams $searchParams,
User $user,
bool $notRead,
?string $beforeNumber,
): SelectBuilder {
if ($searchParams->getMaxSize() !== null) {
$searchParams = $searchParams->withMaxSize($searchParams->getMaxSize() + 1);
}
$builder = $this->selectBuilderFactory
->create()
->from(Notification::ENTITY_TYPE)
->withSearchParams($searchParams)
->buildQueryBuilder()
->select([
Selection::create(
Expr::value(Notification::GROUP_TYPE_EMAIL_RECEIVED),
self::COLUMN_GROUP_TYPE
),
Selection::create(
Expr::concat(
Expr::value(Notification::GROUP_TYPE_EMAIL_RECEIVED),
Expr::value('_'),
),
Attribute::ID
),
Selection::create(
$this->getMaxNumberExpr(),
Notification::ATTR_NUMBER
),
Selection::create(
Expr::value(null),
Notification::ATTR_RELATED_PARENT_ID,
),
Selection::create(
Expr::value(null),
Notification::ATTR_RELATED_PARENT_TYPE,
),
Selection::create(
Expr::switch(
Expr::greater(
Expr::sum(
Expr::switch(
Expr::column(Notification::ATTR_READ),
Expr::value(0),
Expr::value(1),
),
),
0
),
Expr::value(false),
Expr::value(true),
),
Notification::ATTR_READ
),
Selection::create(
Expr::sum(
Expr::switch(
Expr::column(Notification::ATTR_READ),
Expr::value(0),
Expr::value(1),
),
),
self::COLUMN_GROUP_UNREAD_COUNT
),
Selection::create(
Expr::max(Expr::column(Field::CREATED_AT)),
Field::CREATED_AT,
),
Selection::create(
Expr::value(false),
Notification::FIELD_IS_FEATURED,
),
...$this->getNullNoGroupSelections(),
])
->where([
Notification::FIELD_TYPE => Notification::TYPE_EMAIL_RECEIVED,
])
->where([Notification::ATTR_USER_ID => $user->getId()])
->group(Notification::FIELD_TYPE)
->order([])
->order($this->getMaxNumberExpr(), Order::DESC);
if ($beforeNumber) {
$builder->having(
Cond::less(
$this->getMaxNumberExpr(),
Expr::value($beforeNumber)
)
);
}
if ($notRead) {
$builder->where([Notification::ATTR_READ => false]);
}
return $builder;
}
/**
* @throws BadRequest
* @throws Forbidden
*/
private function prepareRestBuilder(
SearchParams $searchParams,
User $user,
bool $notRead,
?string $beforeNumber,
): SelectBuilder {
if ($searchParams->getMaxSize() !== null) {
$searchParams = $searchParams->withMaxSize($searchParams->getMaxSize() + 1);
}
$builder = $this->selectBuilderFactory
->create()
->from(Notification::ENTITY_TYPE)
->withSearchParams($searchParams)
->buildQueryBuilder()
->select([
Selection::create(
Expr::value(null),
self::COLUMN_GROUP_TYPE,
),
Attribute::ID,
Notification::ATTR_NUMBER,
Notification::ATTR_RELATED_PARENT_ID,
Notification::ATTR_RELATED_PARENT_TYPE,
Notification::ATTR_READ,
Selection::create(
Expr::switch(
Expr::column(Notification::ATTR_READ),
Expr::value(0),
Expr::value(1),
),
self::COLUMN_GROUP_UNREAD_COUNT
),
Field::CREATED_AT,
Selection::create(
Expr::value(null),
Notification::FIELD_IS_FEATURED,
),
...$this->noGroupAttributes,
])
->where([
[
'OR' => [
Notification::FIELD_TYPE . '!=' => $this->getRecordGroupNoteTypes(),
Notification::ATTR_RELATED_PARENT_ID => null,
],
],
Notification::FIELD_TYPE . '!=' => Notification::TYPE_EMAIL_RECEIVED,
])
->where([Notification::ATTR_USER_ID => $user->getId()])
->order([])
->order(Notification::ATTR_NUMBER, Order::DESC);
if ($notRead) {
$builder->where([Notification::ATTR_READ => false]);
}
if ($beforeNumber) {
$builder->where([Notification::ATTR_NUMBER . '<' => $beforeNumber]);
}
return $builder;
}
private function getMaxNumberExpr(): Expr
{
return Expr::max(Expr::column(Notification::ATTR_NUMBER));
}
/**
* @internal
* @return string[]
*/
public function getRecordGroupNoteTypes(): array
{
return [
Notification::TYPE_NOTE,
Notification::TYPE_USER_REACTION,
Notification::TYPE_COLLABORATING,
'EventAttendee',
];
}
}

View File

@@ -0,0 +1,233 @@
<?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\Notification;
use Espo\Core\Field\LinkParent;
use Espo\Core\Name\Field;
use Espo\Core\Utils\Id\RecordIdGenerator;
use Espo\Entities\Note;
use Espo\Entities\Notification;
use Espo\Entities\User;
use Espo\Entities\Email;
use Espo\Core\AclManager;
use Espo\Core\WebSocket\Submission;
use Espo\Core\Utils\DateTime as DateTimeUtil;
use Espo\Modules\Crm\Entities\CaseObj;
use Espo\ORM\EntityManager;
use Espo\ORM\Name\Attribute;
use Espo\Tools\Notification\HookProcessor\Params;
use stdClass;
class Service
{
public function __construct(
private EntityManager $entityManager,
private AclManager $aclManager,
private Submission $webSocketSubmission,
private RecordIdGenerator $idGenerator,
) {}
public function notifyAboutMentionInPost(string $userId, Note $note): void
{
$notification = $this->entityManager->getRDBRepositoryByClass(Notification::class)->getNew();
$notification
->setType(Notification::TYPE_MENTION_IN_POST)
->setData(['noteId' => $note->getId()])
->setUserId($userId)
->setRelated(LinkParent::fromEntity($note));
$this->entityManager->saveEntity($notification);
}
/**
* @param string[] $userIdList
* @param ?Params $params Hook parameters. As of v9.2.0.
* @param ?NoteNotifyParams $notifyParams Parameters. As of v10.0.1.
*/
public function notifyAboutNote(
array $userIdList,
Note $note,
?Params $params = null,
?NoteNotifyParams $notifyParams = null,
): void {
$related = null;
if ($note->getRelatedType() === Email::ENTITY_TYPE) {
$related = $this->entityManager
->getRDBRepository(Email::ENTITY_TYPE)
->select([
Attribute::ID,
'sentById',
'createdById',
])
->where([Attribute::ID => $note->getRelatedId()])
->findOne();
}
$now = date(DateTimeUtil::SYSTEM_DATE_TIME_FORMAT);
$collection = $this->entityManager->getCollectionFactory()->create();
$users = $this->entityManager
->getRDBRepositoryByClass(User::class)
->select([
Attribute::ID,
User::ATTR_TYPE,
])
->where([
User::ATTR_IS_ACTIVE => true,
Attribute::ID => $userIdList,
])
->find();
foreach ($users as $user) {
if (!$this->checkUserNoteAccess($user, $note)) {
continue;
}
if ($note->getCreatedById() === $user->getId()) {
continue;
}
if (
$related instanceof Email &&
$related->getSentBy()?->getId() === $user->getId()
) {
continue;
}
if ($related && $related->get('createdById') === $user->getId()) {
continue;
}
$actionId = $params?->actionId;
$isFeatured = false;
if ($this->isUserTargetAssignee($note, $user)) {
$isFeatured = true;
// Do not group notifications about assignment.
$actionId = null;
}
$relatedParent = $note->getParentType() && $note->getParentId() ?
LinkParent::create($note->getParentType(), $note->getParentId()) : null;
if ($notifyParams?->isSuper) {
$relatedParent = $note->getSuperParentType() && $note->getSuperParentId() ?
LinkParent::create($note->getSuperParentType(), $note->getSuperParentId()) : null;
}
$notification = $this->entityManager->getRDBRepositoryByClass(Notification::class)->getNew();
$notification
->set(Attribute::ID, $this->idGenerator->generate())
->set(Field::CREATED_AT, $now)
->setData([Notification::DATE_ATTR_NOTE_ID => $note->getId()])
->setType(Notification::TYPE_NOTE)
->setUserId($user->getId())
->setRelated(LinkParent::fromEntity($note))
->setRelatedParent($relatedParent)
->setActionId($actionId)
->setIsFeatured($isFeatured);
$collection[] = $notification;
}
if (!count($collection)) {
return;
}
$this->entityManager->getMapper()->massInsert($collection);
foreach ($userIdList as $userId) {
$this->webSocketSubmission->submit('newNotification', $userId);
}
}
private function checkUserNoteAccess(User $user, Note $note): bool
{
if ($user->isPortal()) {
if ($note->getRelatedType()) {
/** @todo Revise. */
return
$note->getRelatedType() === Email::ENTITY_TYPE &&
$note->getParentType() === CaseObj::ENTITY_TYPE;
}
return true;
}
if ($note->getRelatedType() && !$this->aclManager->checkScope($user, $note->getRelatedType())) {
return false;
}
if ($note->getParentType() && !$this->aclManager->checkScope($user, $note->getParentType())) {
return false;
}
return true;
}
private function isUserTargetAssignee(Note $note, User $user): bool
{
if (!in_array($note->getType(), [Note::TYPE_ASSIGN, Note::TYPE_CREATE])) {
return false;
}
$noteData = $note->getData();
if (($noteData->{Note::DATA_ATTR_ASSIGNED_USER_ID} ?? null) === $user->getId()) {
return true;
}
$assignedUsers = $noteData->{Note::DATA_ATTR_ASSIGNED_USERS} ??
$noteData->{Note::DATA_ATTR_ADDED_ASSIGNED_USERS} ?? null;
if (!is_array($assignedUsers)) {
return false;
}
foreach ($assignedUsers as $item) {
if (!$item instanceof stdClass) {
continue;
}
if (($item->{Attribute::ID} ?? null) === $user->getId()) {
return true;
}
}
return false;
}
}