CAllCrmDeal::MoveToCategory

  1. Bitrix24 API (v. 23.675.0)
  2. crm
  3. CAllCrmDeal
  4. MoveToCategory
  • Модуль: crm
  • Путь к файлу: ~/bitrix/modules/crm/classes/general/crm_deal.php
  • Класс: \CAllCrmDeal
  • Вызов: CAllCrmDeal::MoveToCategory
static function MoveToCategory($ID, $newCategoryID, array $options = null)
{
	if(!is_int($ID))
	{
		$ID = (int)$ID;
	}

	if($ID <= 0)
	{
		return DealCategoryChangeError::GENERAL;
	}

	if(!is_int($newCategoryID))
	{
		$newCategoryID = (int)$newCategoryID;
	}

	if($newCategoryID !== 0 && !DealCategory::exists($newCategoryID))
	{
		return DealCategoryChangeError::CATEGORY_NOT_FOUND;
	}

	if($options === null)
	{
		$options = array();
	}

	$dbResult = self::GetListEx(
		array(),
		array('ID' => $ID, 'CHECK_PERMISSIONS' => 'N'),
		false,
		false,
		array('ID', 'CATEGORY_ID', 'STAGE_ID', 'ASSIGNED_BY_ID', 'OPENED')
	);

	$fields = $dbResult->Fetch();
	if(!is_array($fields))
	{
		return DealCategoryChangeError::NOT_FOUND;
	}

	$categoryID = isset($fields['CATEGORY_ID']) ? (int)$fields['CATEGORY_ID'] : 0;
	if($categoryID === $newCategoryID)
	{
		return DealCategoryChangeError::CATEGORY_NOT_CHANGED;
	}

	$assignedByID = isset($fields['ASSIGNED_BY_ID']) ? (int)$fields['ASSIGNED_BY_ID'] : 0;
	if($assignedByID <= 0)
	{
		return DealCategoryChangeError::RESPONSIBLE_NOT_FOUND;
	}

	$stageID = isset($fields['STAGE_ID']) ? $fields['STAGE_ID'] : '';
	if($stageID === '')
	{
		return DealCategoryChangeError::STAGE_NOT_FOUND;
	}

	$checkRunningBizProcess = !isset($options['ENABLE_WORKFLOW_CHECK']) || $options['ENABLE_WORKFLOW_CHECK'] === true;
	if($checkRunningBizProcess && \CCrmBizProcHelper::HasRunningWorkflows(CCrmOwnerType::Deal, $ID))
	{
		return DealCategoryChangeError::HAS_WORKFLOWS;
	}

	$processStageID = $options['PREFERRED_STAGE_ID'] ?? '';
	$event = new \Bitrix\Main\Event(
		'crm',
		'OnBeforeDealMoveToCategory',
		[
			'id' => $ID,
			'categoryId' => $newCategoryID,
			'stageId' => $processStageID,
		]
	);
	$event->send();
	/** @var @var \Bitrix\Main\EventResult $eventResult */
	foreach ($event->getResults() as $eventResult)
	{
		if ($eventResult->getType() === \Bitrix\Main\EventResult::ERROR)
		{
			return DealCategoryChangeError::USER_EVENT_FAILURE;
		}
		$parameters = $eventResult->getParameters();
		if (isset($parameters['categoryId']))
		{
			$newCategoryID = (int)$parameters['categoryId'];
			if($categoryID === $newCategoryID)
			{
				return DealCategoryChangeError::CATEGORY_NOT_CHANGED;
			}
			if($newCategoryID !== 0 && !DealCategory::exists($newCategoryID))
			{
				return DealCategoryChangeError::CATEGORY_NOT_FOUND;
			}
		}
		if (isset($parameters['stageId']))
		{
			$processStageID = $parameters['stageId'];
		}
	}

	$updateOperationRestriction = Crm\Restriction\RestrictionManager::getUpdateOperationRestriction(new Crm\ItemIdentifier(
		\CCrmOwnerType::Deal,
		(int)$ID
	));
	if (!$updateOperationRestriction->hasPermission())
	{
		return DealCategoryChangeError::RESTRICTION_APPLIED;
	}

	$successStageID = DealCategory::prepareStageID($newCategoryID, 'WON');
	$failureStageID = DealCategory::prepareStageID($newCategoryID, 'LOSE');
	$categoryStages = self::GetStages($newCategoryID);
	if (!$processStageID || !array_key_exists($processStageID, $categoryStages))
	{
		//Looking for first process stage ID
		foreach (array_keys($categoryStages) as $statusID)
		{
			if ($successStageID !== $statusID)
			{
				$processStageID = $statusID;
				break;
			}
		}

		if($processStageID === '')
		{
			$processStageID = DealCategory::prepareStageID($newCategoryID, 'NEW');
		}
	}

	$semanticID = self::GetSemanticID($stageID, $categoryID);
	$newStageID = $processStageID;
	if (!isset($options['PREFERRED_STAGE_ID']))
	{
		if ($semanticID === Bitrix\Crm\PhaseSemantics::SUCCESS)
		{
			$newStageID = $successStageID;
		}
		elseif ($semanticID === Bitrix\Crm\PhaseSemantics::FAILURE)
		{
			$newStageID = $failureStageID;
		}
	}
	$newStageSemanticID = self::GetSemanticID($newStageID, $newCategoryID);

	$connection = \Bitrix\Main\Application::getConnection();
	$sqlHelper = $connection->getSqlHelper();

	$escapedCategoryId = (int)$newCategoryID;
	$escapedStageId = $sqlHelper->forSql($newStageID);
	$escapedNewStageSemanticId = $sqlHelper->forSql($newStageSemanticID);
	$now = $connection->getSqlHelper()->getCurrentDateTimeFunction();

	$sql = "UPDATE b_crm_deal SET "
		. " CATEGORY_ID = {$escapedCategoryId},"
		. " STAGE_ID = '{$escapedStageId}',"
		. (
			($semanticID != $newStageSemanticID)
				? " STAGE_SEMANTIC_ID='{$escapedNewStageSemanticId}', "
				: ''
		)
		. " DATE_MODIFY = {$now} "
		. " WHERE ID = {$ID}"
	;

	$connection->query($sql);

	$currentFields = array_merge($fields, [
		'CATEGORY_ID' => $newCategoryID,
		'STAGE_ID' => $newStageID,
	]);

	Bitrix\Crm\Timeline\DealController::getInstance()->onModify($ID, [
		'PREVIOUS_FIELDS' => $fields,
		'CURRENT_FIELDS' => $currentFields,
	]);

	//region Update Permissions
	$permissionEntityController = Crm\Security\Manager::getEntityController(CCrmOwnerType::Deal);
	$permissionEntityController->unregister(DealCategory::convertToPermissionEntityType($categoryID), $ID);

	self::clearCategoryCache($ID);
	$entityAttrs = self::BuildEntityAttr(
		$assignedByID,
			array(
				'STAGE_ID' => $newStageID,
				'OPENED' => isset($fields['OPENED']) ? $fields['OPENED'] : 'N'
			)
	);
	$userPermissions = CCrmPerms::GetUserPermissions($assignedByID);
	$permissionEntityType = DealCategory::convertToPermissionEntityType($newCategoryID);
	self::PrepareEntityAttrs(
		$entityAttrs,
		$userPermissions->GetPermType($permissionEntityType, 'WRITE', $entityAttrs)
	);

	$securityRegisterOptions = (new \Bitrix\Crm\Security\Controller\RegisterOptions())
		->setEntityAttributes($entityAttrs)
		->setEntityFields($currentFields)
	;
	$permissionEntityController->register($permissionEntityType, $ID, $securityRegisterOptions);

	\Bitrix\Crm\Counter\Monitor::getInstance()->onEntityUpdate(
		CCrmOwnerType::Deal,
		$fields,
		$currentFields
	);
	//endregion
	if(!isset($options['REGISTER_STATISTICS']) || $options['REGISTER_STATISTICS'] === true)
	{
		DealStageHistoryEntry::processCagegoryChange($ID);
		DealSumStatisticEntry::processCagegoryChange($ID);
		DealInvoiceStatisticEntry::processCagegoryChange($ID);
		DealActivityStatisticEntry::processCagegoryChange($ID);
	}
	$timestamp = time() + CTimeZone::GetOffset();
	$userID = isset($options['USER_ID']) ? (int)$options['USER_ID'] : 0;
	if($userID <= 0)
	{
		$userID = CCrmSecurityHelper::GetCurrentUserID();
	}

	$eventEntity = new CCrmEvent();
	$eventEntity->Add(
		array(
			'USER_ID' => $userID,
			'ENTITY_ID' => $ID,
			'ENTITY_TYPE' => CCrmOwnerType::DealName,
			'EVENT_TYPE' => CCrmEvent::TYPE_CHANGE,
			'EVENT_NAME' => GetMessage('CRM_FIELD_COMPARE_DEAL_CATEGORY'),
			'DATE_CREATE' => ConvertTimeStamp($timestamp, 'FULL', SITE_ID),
			'EVENT_TEXT_1' => DealCategory::getName($categoryID),
			'EVENT_TEXT_2' => DealCategory::getName($newCategoryID)
		),
		false
	);

	$event = new \Bitrix\Main\Event(
		'crm',
		'OnAfterDealMoveToCategory',
		[
			'id' => $ID,
			'categoryId' => $newCategoryID,
			'stageId' => $newStageID,
		]
	);
	$event->send();

	return DealCategoryChangeError::NONE;
}

Добавить комментарий