• Модуль: imopenlines
  • Путь к файлу: ~/bitrix/modules/imopenlines/lib/tracker.php
  • Класс: BitrixImOpenLinesTracker
  • Вызов: Tracker::bindExpectationToChat
public function bindExpectationToChat(string $trackId, Chat $chat, Session $session): void
{
	if (!Loader::includeModule('crm'))
	{
		return;
	}

	$expectation = $this->findExpectationByTrackId($trackId);
	if ($expectation)
	{
		$crmManager = new Crm($session);
		$crmManager
			->setSkipSearch()
			->setSkipCreate()
			->setSkipAutomationTriggerFirstMessage();

		$selector = $crmManager->getEntityManageFacility()->getSelector();

		$entityType = $expectation['CRM_ENTITY_TYPE'] ?? null;
		$entityId = (int)($expectation['CRM_ENTITY_ID'] ?? 0);
		$contactId = (int)($expectation['CRM_CONTACT_ID'] ?? 0);
		$companyId = (int)($expectation['CRM_COMPANY_ID'] ?? 0);
		$dealId = (int)($expectation['CRM_DEAL_ID'] ?? 0);
		$leadId = (int)($expectation['CRM_LEAD_ID'] ?? 0);

		$crmFields = [];
		$updateSession = [];
		if ($dealId)
		{
			$crmFields['DEAL'] = $dealId;
			$updateSession['CRM_CREATE_DEAL'] = 'Y';
			if (!$entityId)
			{
				$entityType = CCrmOwnerType::DealName;
				$entityId = $dealId;
			}
			$selector->setEntity(CCrmOwnerType::Deal, $entityId);
		}
		if ($leadId)
		{
			$crmFields['LEAD'] = $leadId;
			$updateSession['CRM_CREATE_LEAD'] = 'Y';
			if (!$entityId)
			{
				$entityType = CCrmOwnerType::LeadName;
				$entityId = $leadId;
			}
			$selector->setEntity(CCrmOwnerType::Lead, $leadId);
		}
		if ($contactId)
		{
			$crmFields['CONTACT'] = $contactId;
			$updateSession['CRM_CREATE_CONTACT'] = 'Y';
			$selector->setEntity(CCrmOwnerType::Contact, $contactId);
		}
		if ($companyId)
		{
			$crmFields['COMPANY'] = $companyId;
			$updateSession['CRM_CREATE_COMPANY'] = 'Y';
			$selector->setEntity(CCrmOwnerType::Company, $companyId);
		}
		if ($entityType && $entityId)
		{
			$crmFields['ENTITY_TYPE'] = $entityType;
			$crmFields['ENTITY_ID'] = $entityId;
			$selector->setEntity(CCrmOwnerType::ResolveID($entityType), $entityId);
		}

		if ($crmFields)
		{
			$registerActivityResult = $crmManager->registrationChanges();
			if ($registerActivityResult->isSuccess())
			{
				$crmManager->sendCrmImMessages();

				$updateSession['CRM_ACTIVITY_ID'] = $registerActivityResult->getResult();
				$session->updateCrmFlags($updateSession);

				$crmFields['CRM'] = 'Y';
				$chat->setCrmFlag($crmFields);

				$crmManager->updateUserConnector();
			}
		}
	}
}