• Модуль: crm
  • Путь к файлу: ~/bitrix/modules/crm/lib/integration/report/handler/customers/regularcustomers.php
  • Класс: Bitrix\Crm\Integration\Report\Handler\Customers\RegularCustomers
  • Вызов: RegularCustomers::prepareQuery
public function prepareQuery()
{
	$filterParameters = $this->getFilterParameters();

	$query1 = DealTable::query();
	$query2 = DealTable::query();

	$this->addToQueryFilterCase($query1, $filterParameters);
	$this->addTimePeriodToQuery($query1, $filterParameters['TIME_PERIOD']);

	$this->addToQueryFilterCase($query2, $filterParameters);
	$this->addTimePeriodToQuery($query2, $filterParameters['TIME_PERIOD']);

	$this->addPermissionsCheck($query1);
	$this->addPermissionsCheck($query2);

	$query1
		->addSelect(new \Bitrix\Main\Entity\ExpressionField("OWNER_TYPE", "'CONTACT'"))
		->addSelect("CONTACT.ID", "OWNER_ID")
		->addSelect("CURRENCY_ID")
		->addSelect(Query::expr()->count("ID"), "DEAL_COUNT")
		->addSelect(Query::expr()->sum("OPPORTUNITY"), "TOTAL_AMOUNT")
		->whereNotNull("CONTACT.ID")
		->where("STAGE_SEMANTIC_ID", PhaseSemantics::SUCCESS)
		->where(Query::filter()->logic('or')->where('COMPANY_ID', 0)->whereNull('COMPANY_ID'));

	$query2
		->addSelect(new \Bitrix\Main\Entity\ExpressionField("OWNER_TYPE", "'COMPANY'"))
		->addSelect("COMPANY.ID", "OWNER_ID")
		->addSelect("CURRENCY_ID")
		->addSelect(Query::expr()->count("ID"), "DEAL_COUNT")
		->addSelect(Query::expr()->sum("OPPORTUNITY"), "TOTAL_AMOUNT")
		->whereNotNull("COMPANY.ID")
		->where("STAGE_SEMANTIC_ID", PhaseSemantics::SUCCESS);

	$query1->unionAll($query2);

	$mainQuery = "
		SELECT 
			OWNER_TYPE, 
			CURRENCY_ID, 
			DEAL_COUNT, 
			COUNT(DEAL_COUNT) AS CLIENT_COUNT, 
			SUM(TOTAL_AMOUNT) AS TOTAL_AMOUNT 
		FROM ({$query1->getQuery()}) t 
		GROUP BY OWNER_TYPE, CURRENCY_ID, DEAL_COUNT
	";

	return $mainQuery;
}