• Модуль: crm
  • Путь к файлу: ~/bitrix/modules/crm/lib/controller/action/entity/mergebatchaction.php
  • Класс: Bitrix\Crm\Controller\Action\Entity\MergeBatchAction
  • Вызов: MergeBatchAction::run
public function run(array $params)
{
	if(!Crm\Security\EntityAuthorization::isAuthorized())
	{
		$this->addError(new Main\Error('Access denied.'));
		return null;
	}

	$entityTypeID = isset($params['entityTypeId']) ? (int)$params['entityTypeId'] : \CCrmOwnerType::Undefined;
	if($entityTypeID === \CCrmOwnerType::Undefined)
	{
		$this->addError(new Main\Error('The parameter entityTypeId is required.'));
		return null;
	}

	$entity = Crm\Entity\EntityManager::resolveByTypeID($entityTypeID);

	$entityIDs = isset($params['entityIds']) && is_array($params['entityIds']) ? $params['entityIds'] : null;
	$effectiveEntityIDs = [];

	if ($entityTypeID === \CCrmOwnerType::Deal)
	{
		$restriction = \Bitrix\Crm\Restriction\RestrictionManager::getWebFormResultsRestriction();
		if (!$restriction->hasPermission())
		{
			$restrictedItemIds = $restriction->filterRestrictedItemIds(
				$entityTypeID,
				$entityIDs
			);
			if (!empty($restrictedItemIds))
			{
				Container::getInstance()->getLocalization()->loadMessages();
				$this->addError(new Main\Error(Main\Localization\Loc::getMessage('CRM_FEATURE_RESTRICTION_ERROR')));
				return null;
			}
		}
	}

	foreach($entityIDs as $entityID)
	{
		if($entity->isExists($entityID))
		{
			$effectiveEntityIDs[] = $entityID;
		}
	}

	if(empty($effectiveEntityIDs))
	{
		$this->addError(new Main\Error('The parameter entityIds does not contains valid elements.'));
		return null;
	}

	if(count($effectiveEntityIDs) < 2)
	{
		$this->addError(new Main\Error('The parameter entityIds must contains at least two elements.'));
		return null;
	}

	//TODO: Resolve Root entity through API
	$rootEntityID = array_shift($effectiveEntityIDs);

	$entity = Crm\Entity\EntityManager::resolveByTypeID($entityTypeID);
	if(!$entity->isExists($rootEntityID))
	{
		return [ 'STATUS' => 'NOT_FOUND' ];
	}

	$currentUserID = \CCrmSecurityHelper::GetCurrentUserID();
	$enablePermissionCheck = !\CCrmPerms::IsAdmin($currentUserID);
	$merger = Crm\Merger\EntityMerger::create($entityTypeID, $currentUserID, $enablePermissionCheck);
	$merger->setConflictResolutionMode(Crm\Merger\ConflictResolutionMode::ASK_USER);

	$result = [
		'STATUS' => 'SUCCESS',
		'ENTITY_IDS' => $effectiveEntityIDs
	];

	//TODO: Resolve Root entity through API
	try
	{
		$merger->mergeBatch($effectiveEntityIDs, $rootEntityID);
	}
	catch(Crm\Merger\EntityMergerException $e)
	{
		if($e->getCode() === Crm\Merger\EntityMergerException::CONFLICT_OCCURRED)
		{
			$result['STATUS'] = 'CONFLICT';
		}
		else
		{
			$result['STATUS'] = 'ERROR';
		}
		$this->addError(new Main\Error($e->getLocalizedMessage()));
	}
	catch(\Exception $e)
	{
		$result['STATUS'] = 'ERROR';
		$this->addError(new Main\Error($e->getMessage()));
	}
	return $result;
}