Initial commit

This commit is contained in:
root
2026-01-19 17:44:46 +01:00
commit 823af8b11d
8721 changed files with 1130846 additions and 0 deletions

View File

@@ -0,0 +1,60 @@
<?php
/************************************************************************
* This file is part of EspoCRM.
*
* EspoCRM Open Source CRM application.
* Copyright (C) 2014-2025 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,76 @@
<?php
/************************************************************************
* This file is part of EspoCRM.
*
* EspoCRM Open Source CRM application.
* Copyright (C) 2014-2025 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,217 @@
<?php
/************************************************************************
* This file is part of EspoCRM.
*
* EspoCRM Open Source CRM application.
* Copyright (C) 2014-2025 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\Core\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
) {}
/**
* @param array<string, mixed> $options
*/
public function afterSave(Entity $entity, array $options): void
{
$entityType = $entity->getEntityType();
if (!$entity instanceof CoreEntity) {
return;
}
$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;
}
$assignmentNotificationsEntityList = $this->config->get('assignmentNotificationsEntityList') ?? [];
if (
(!$force || !$hasStream) &&
!in_array($entityType, $assignmentNotificationsEntityList)
) {
return;
}
$notificator = $this->getNotificator($entityType);
$params = AssignmentNotificatorParams::create()->withRawOptions($options);
$saveContext = SaveContext::obtainFromRawOptions($options);
if ($saveContext) {
$params = $params->withActionId($saveContext->getActionId());
}
$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']);
}
}

View File

@@ -0,0 +1,37 @@
<?php
/************************************************************************
* This file is part of EspoCRM.
*
* EspoCRM Open Source CRM application.
* Copyright (C) 2014-2025 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,428 @@
<?php
/************************************************************************
* This file is part of EspoCRM.
*
* EspoCRM Open Source CRM application.
* Copyright (C) 2014-2025 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;
}
$userList = $this->getSubscriberList($parentType, $parentId, $note->isInternal());
$userIdMetList = [];
foreach ($userList as $user) {
$userIdMetList[] = $user->getId();
}
if ($superParentType && $superParentId) {
$additionalUserList = $this->getSubscriberList(
$superParentType,
$superParentId,
$note->isInternal()
);
foreach ($additionalUserList as $user) {
if (
$user->isPortal() ||
in_array($user->getId(), $userIdMetList)
) {
continue;
}
$userIdMetList[] = $user->getId();
$userList[] = $user;
}
}
$targetType = $note->getRelatedType() ? $note->getRelatedType() : $parentType;
// This is correct.
$skipAclCheck = !$note->isAclProcessed();
$teamIdList = null;
$userIdList = null;
if (!$skipAclCheck) {
$teamIdList = $note->getLinkMultipleIdList(Field::TEAMS);
$userIdList = $note->getLinkMultipleIdList('users');
}
$notifyUserIdList = [];
foreach ($userList as $user) {
if ($skipAclCheck) {
$notifyUserIdList[] = $user->getId();
continue;
}
/** @var string[] $userIdList */
/** @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, $userIdList)) {
continue;
}
$notifyUserIdList[] = $user->getId();
}
$this->processNotify($note, array_unique($notifyUserIdList), $params);
}
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): 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;
}
$this->service->notifyAboutNote($filteredUserIdList, $note, $params);
}
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-2025 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,470 @@
<?php
/************************************************************************
* This file is part of EspoCRM.
*
* EspoCRM Open Source CRM application.
* Copyright (C) 2014-2025 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\WhereItem;
use Espo\ORM\Query\SelectBuilder;
use Espo\Tools\Stream\NoteAccessControl;
class RecordService
{
public function __construct(
private EntityManager $entityManager,
private Acl $acl,
private Metadata $metadata,
private NoteAccessControl $noteAccessControl,
private SelectBuilderFactory $selectBuilderFactory,
private Config $config,
) {}
/**
* Get notifications for a user.
*
* @return RecordCollection<Notification>
* @throws Error
* @throws BadRequest
* @throws Forbidden
*/
public function get(User $user, SearchParams $searchParams): RecordCollection
{
$queryBuilder = $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 ($this->isGroupingEnabled()) {
$queryBuilder->where($this->getActionIdWhere($user->getId()));
}
$offset = $searchParams->getOffset();
$limit = $searchParams->getMaxSize();
if ($limit) {
$queryBuilder->limit($offset, $limit + 1);
}
$ignoreScopeList = $this->getIgnoreScopeList();
if ($ignoreScopeList !== []) {
$queryBuilder->where([
'OR' => [
'relatedParentType' => null,
'relatedParentType!=' => $ignoreScopeList,
],
]);
}
$query = $queryBuilder->build();
$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->getGroupedCountMap($collection, $user->getId());
$ids = [];
$actionIds = [];
foreach ($collection as $i => $entity) {
if ($i === $limit) {
break;
}
$ids[] = $entity->getId();
$groupedCount = null;
if ($entity->getActionId() && $this->isGroupingEnabled()) {
$actionIds[] = $entity->getActionId();
$groupedCount = $groupedCountMap[$entity->getActionId()] ?? 0;
}
$entity->set('groupedCount', $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 {
$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());
}
public function getNotReadCount(string $userId): int
{
$whereClause = [
Notification::ATTR_USER_ID => $userId,
Notification::ATTR_READ => false,
];
$ignoreScopeList = $this->getIgnoreScopeList();
if (count($ignoreScopeList)) {
$whereClause[] = [
'OR' => [
'relatedParentType' => null,
'relatedParentType!=' => $ignoreScopeList,
]
];
}
$builder = $this->entityManager
->getRDBRepositoryByClass(Notification::class)
->where($whereClause);
if ($this->isGroupingEnabled()) {
$builder->where($this->getActionIdWhere($userId));
}
return $builder->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) {
$parent = $this->entityManager->getEntityById($parentType, $parentId);
if ($parent) {
$note->set('parentName', $parent->get(Field::NAME));
}
}
} 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) {
$related = $this->entityManager->getEntityById($relatedType, $relatedId);
if ($related) {
$note->set('relatedName', $related->get(Field::NAME));
}
}
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 getGroupedCountMap(EntityCollection $collection, string $userId): array
{
if (!$this->isGroupingEnabled()) {
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 isGroupingEnabled(): bool
{
// @todo Param in preferences?
return (bool) ($this->config->get('notificationGrouping') ?? true);
}
}

View File

@@ -0,0 +1,187 @@
<?php
/************************************************************************
* This file is part of EspoCRM.
*
* EspoCRM Open Source CRM application.
* Copyright (C) 2014-2025 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;
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::createFromEntity($note));
$this->entityManager->saveEntity($notification);
}
/**
* @param string[] $userIdList
* @param ?Params $params Parameters. As of v9.2.0.
*/
public function notifyAboutNote(array $userIdList, Note $note, ?Params $params = 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
->getRDBRepository(User::ENTITY_TYPE)
->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;
if (
in_array($note->getType(), [Note::TYPE_ASSIGN, Note::TYPE_CREATE]) &&
($note->getData()->assignedUserId ?? null) === $user->getId()
) {
// Do not group notifications about assignment.
$actionId = null;
}
$notification = $this->entityManager->getRDBRepositoryByClass(Notification::class)->getNew();
$notification
->set(Attribute::ID, $this->idGenerator->generate())
->set(Field::CREATED_AT, $now)
->setData(['noteId' => $note->getId()])
->setType(Notification::TYPE_NOTE)
->setUserId($user->getId())
->setRelated(LinkParent::createFromEntity($note))
->setRelatedParent(
$note->getParentType() && $note->getParentId() ?
LinkParent::create($note->getParentType(), $note->getParentId()) : null
)
->setActionId($actionId);
$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;
}
}