*/ class CaseObj extends \Espo\Core\Repositories\Database implements Di\ServiceFactoryAware { use Di\ServiceFactorySetter; protected ?StreamService $streamService = null; protected function afterSave(Entity $entity, array $options = []) { parent::afterSave($entity, $options); $this->handleAfterSaveContacts($entity); } protected function getStreamService(): StreamService { if (!$this->streamService) { /** @var StreamService */ $service = $this->serviceFactory->create('Stream'); $this->streamService = $service; } return $this->streamService; } protected function handleAfterSaveContacts(Entity $entity): void { if (!$entity->isAttributeChanged('contactId')) { return; } $contactId = $entity->get('contactId'); $contactIdList = $entity->get('contactsIds') ?? []; $fetchedContactId = $entity->getFetched('contactId'); if ($fetchedContactId) { $previousPortalUser = $this->entityManager ->getRDBRepository('User') ->select(['id']) ->where([ 'contactId' => $fetchedContactId, 'type' => 'portal', ]) ->findOne(); if ($previousPortalUser) { $this->getStreamService()->unfollowEntity($entity, $previousPortalUser->getId()); } } if (!$contactId) { if ($fetchedContactId) { $this->unrelate($entity, 'contacts', $fetchedContactId); } return; } $portalUser = $this->entityManager ->getRDBRepository('User') ->select(['id']) ->where([ 'contactId' => $contactId, 'type' => 'portal', 'isActive' => true, ]) ->findOne(); if ($portalUser) { $this->getStreamService()->followEntity($entity, $portalUser->getId(), true); } if (!in_array($contactId, $contactIdList) && !$this->isRelated($entity, 'contacts', $contactId)) { $this->relate($entity, 'contacts', $contactId); } } }