private static function loadBulk($entityTypeID, array &$entityIDs, array &$itemMap, array $options = null)
 {
     /** @var DuplicateEntityRanking[] $itemMap */
     if ($entityTypeID !== \CCrmOwnerType::Contact && $entityTypeID !== \CCrmOwnerType::Company && $entityTypeID !== \CCrmOwnerType::Lead) {
         return;
     }
     if (!is_array($options)) {
         $options = array();
     }
     $checkPermissions = isset($options['CHECK_PERMISSIONS']) ? (bool) $options['CHECK_PERMISSIONS'] : false;
     $userID = isset($options['USER_ID']) ? (int) $options['USER_ID'] : 0;
     $permissions = $checkPermissions ? \CCrmPerms::GetUserPermissions($userID) : null;
     $limit = isset($options['LIMIT']) ? (int) $options['LIMIT'] : 3000;
     if ($limit <= 0) {
         $limit = 3000;
     }
     $length = count($entityIDs);
     if ($length === 0) {
         return;
     }
     while ($length > 0) {
         if ($length <= $limit) {
             $ids = $entityIDs;
             unset($entityIDs);
             $entityIDs = array();
         } else {
             $ids = array_splice($entityIDs, 0, $limit);
         }
         $length = count($entityIDs);
         if (empty($ids)) {
             continue;
         }
         if ($entityTypeID === \CCrmOwnerType::Lead) {
             $dbResult = Entity\DuplicateEntityStatisticsTable::getList(array('select' => array('ENTITY_ID', 'RANKING_DATA'), 'filter' => array('ENTITY_TYPE_ID' => \CCrmOwnerType::Lead, 'ENTITY_ID' => $ids)));
             while ($fields = $dbResult->fetch()) {
                 $entityID = intval($fields['ENTITY_ID']);
                 $key = "{$entityTypeID}_{$entityID}";
                 if (!isset($itemMap[$key])) {
                     continue;
                 }
                 if (isset($fields['RANKING_DATA']) && $fields['RANKING_DATA'] !== '') {
                     $data = unserialize($fields['RANKING_DATA']);
                     /** @var DuplicateEntityRanking $ranking */
                     $ranking = $itemMap[$key];
                     $ranking->lastChanged = isset($data['LAST_CHANGED']) ? $data['LAST_CHANGED'] : 0;
                     $ranking->completeness = isset($data['COMPLETENESS']) ? $data['COMPLETENESS'] : 0;
                     if ($checkPermissions) {
                         $ranking->editable = \CCrmLead::CheckUpdatePermission($entityID, $permissions);
                         $ranking->deleteable = \CCrmLead::CheckDeletePermission($entityID, $permissions);
                     }
                 }
             }
         } else {
             $query = new Main\Entity\Query(Entity\DuplicateEntityStatisticsTable::getEntity());
             $query->addSelect('ENTITY_ID');
             $query->addSelect('RANKING_DATA');
             $query->addFilter('ENTITY_ID', $ids);
             $query->addFilter('ENTITY_TYPE_ID', $entityTypeID);
             if ($entityTypeID === \CCrmOwnerType::Contact) {
                 $subQuery = new Main\Entity\Query(DealTable::getEntity());
                 $subQuery->addSelect('CONTACT_ID');
                 $subQuery->addFilter('CONTACT_ID', $ids);
                 $subQuery->addSelect('QTY');
                 $subQuery->registerRuntimeField('', new Main\Entity\ExpressionField('QTY', 'COUNT(*)'));
                 $referenceField = new Main\Entity\ReferenceField('D', Main\Entity\Base::getInstanceByQuery($subQuery), array('=this.ENTITY_ID' => 'ref.CONTACT_ID'), array('join_type' => 'LEFT'));
             } else {
                 $subQuery = new Main\Entity\Query(DealTable::getEntity());
                 $subQuery->addSelect('COMPANY_ID');
                 $subQuery->addFilter('COMPANY_ID', $ids);
                 $subQuery->addSelect('QTY');
                 $subQuery->registerRuntimeField('', new Main\Entity\ExpressionField('QTY', 'COUNT(*)'));
                 $referenceField = new Main\Entity\ReferenceField('D', Main\Entity\Base::getInstanceByQuery($subQuery), array('=this.ENTITY_ID' => 'ref.COMPANY_ID'), array('join_type' => 'LEFT'));
             }
             $query->registerRuntimeField('', $referenceField);
             $query->addSelect('D.QTY', 'QTY');
             $dbResult = $query->exec();
             while ($fields = $dbResult->fetch()) {
                 $entityID = intval($fields['ENTITY_ID']);
                 $key = "{$entityTypeID}_{$entityID}";
                 if (!isset($itemMap[$key])) {
                     continue;
                 }
                 $itemMap[$key]->referenceCount = isset($fields['QTY']) ? intval($fields['QTY']) : 0;
                 if (isset($fields['RANKING_DATA']) && $fields['RANKING_DATA'] !== '') {
                     $data = unserialize($fields['RANKING_DATA']);
                     /** @var DuplicateEntityRanking $ranking */
                     $ranking = $itemMap[$key];
                     $ranking->lastChanged = isset($data['LAST_CHANGED']) ? $data['LAST_CHANGED'] : 0;
                     $ranking->completeness = isset($data['COMPLETENESS']) ? $data['COMPLETENESS'] : 0;
                     if ($checkPermissions) {
                         if ($entityTypeID === \CCrmOwnerType::Contact) {
                             $ranking->editable = \CCrmContact::CheckUpdatePermission($entityID, $permissions);
                             $ranking->deleteable = \CCrmContact::CheckDeletePermission($entityID, $permissions);
                         } else {
                             $ranking->editable = \CCrmCompany::CheckUpdatePermission($entityID, $permissions);
                             $ranking->deleteable = \CCrmCompany::CheckDeletePermission($entityID, $permissions);
                         }
                     }
                 }
             }
         }
     }
 }
Example #2
0
 /** @return array */
 public function getList(array $params)
 {
     /** @var Filter $filter */
     $filter = isset($params['filter']) ? $params['filter'] : null;
     if (!$filter instanceof Filter) {
         throw new Main\ObjectNotFoundException("The 'filter' is not found in params.");
     }
     $permissionSql = '';
     if ($this->enablePermissionCheck) {
         $permissionSql = $this->preparePermissionSql();
         if ($permissionSql === false) {
             //Access denied;
             return array();
         }
     }
     $period = $filter->getPeriod();
     $periodStartDate = $period['START'];
     $periodEndDate = $period['END'];
     $query = new Query(DealStageHistoryTable::getEntity());
     $query->addSelect('STAGE_ID');
     $query->addSelect('QTY');
     $query->registerRuntimeField('', new ExpressionField('QTY', 'COUNT(DISTINCT OWNER_ID)'));
     $typeID = $filter->getExtraParam('typeID', HistoryEntryType::UNDEFINED);
     if ($typeID !== HistoryEntryType::UNDEFINED) {
         $query->addFilter('=TYPE_ID', $typeID);
         if ($typeID === HistoryEntryType::CREATION) {
             $query->addFilter('>=START_DATE', $periodStartDate);
             $query->addFilter('<=START_DATE', $periodEndDate);
         } elseif ($typeID === HistoryEntryType::MODIFICATION) {
             $query->addFilter('>=CREATED_TIME', $periodStartDate);
             $query->addFilter('<=CREATED_TIME', $periodEndDate);
         } elseif ($typeID === HistoryEntryType::FINALIZATION) {
             $query->addFilter('>=END_DATE', $periodStartDate);
             $query->addFilter('<=END_DATE', $periodEndDate);
         }
     }
     if ($this->enablePermissionCheck && is_string($permissionSql) && $permissionSql !== '') {
         $query->addFilter('@OWNER_ID', new SqlExpression($permissionSql));
     }
     $responsibleIDs = $filter->getResponsibleIDs();
     if (!empty($responsibleIDs)) {
         $query->addFilter('@RESPONSIBLE_ID', $responsibleIDs);
     }
     $query->addGroup('STAGE_ID');
     $dbResult = $query->exec();
     //Trace('sql', Query::getLastQuery(), 1);
     $result = array();
     while ($ary = $dbResult->fetch()) {
         $result[] = $ary;
     }
     return $result;
 }
 public function calculateEntityCount(DuplicateCriterion $criterion, array $options = null)
 {
     $entityTypeID = $this->getEntityTypeID();
     $enablePermissionCheck = $this->isPermissionCheckEnabled();
     $userID = $this->getUserID();
     $query = new Main\Entity\Query(DuplicateCommunicationMatchCodeTable::getEntity());
     $query->addSelect('QTY');
     $query->registerRuntimeField('', new Main\Entity\ExpressionField('QTY', 'COUNT(*)'));
     $query->addFilter('=ENTITY_TYPE_ID', $entityTypeID);
     if ($enablePermissionCheck) {
         $permissionSql = $this->preparePermissionSql();
         if ($permissionSql === false) {
             //Access denied;
             return 0;
         }
         if (is_string($permissionSql) && $permissionSql !== '') {
             $query->addFilter('@ENTITY_ID', new Main\DB\SqlExpression($permissionSql));
         }
     }
     $matches = $criterion->getMatches();
     $type = isset($matches['TYPE']) ? $matches['TYPE'] : '';
     if ($type === '') {
         throw new Main\ArgumentException("Parameter 'TYPE' is required.", 'matches');
     }
     $value = isset($matches['VALUE']) ? $matches['VALUE'] : '';
     if ($type === '') {
         throw new Main\ArgumentException("Parameter 'VALUE' is required.", 'matches');
     }
     $query->addFilter('=TYPE', $type);
     $query->addFilter('=VALUE', $value);
     $rootEntityID = 0;
     if (is_array($options) && isset($options['ROOT_ENTITY_ID'])) {
         $rootEntityID = (int) $options['ROOT_ENTITY_ID'];
     }
     if ($rootEntityID > 0) {
         $query->addFilter('!ENTITY_ID', $rootEntityID);
         $query->addFilter('!@ENTITY_ID', DuplicateIndexMismatch::prepareQueryField($criterion, $entityTypeID, $rootEntityID, $userID));
     }
     $limit = 0;
     if (is_array($options) && isset($options['LIMIT'])) {
         $limit = (int) $options['LIMIT'];
     }
     if ($limit > 0) {
         $query->setLimit($limit);
     }
     $dbResult = $query->exec();
     $fields = $dbResult->fetch();
     return is_array($fields) && isset($fields['QTY']) ? intval($fields['QTY']) : 0;
 }
Example #4
0
 protected function processActionShowObjectInGrid()
 {
     if (!$this->checkRequiredGetParams(array('objectId'))) {
         $this->sendJsonErrorResponse();
     }
     /** @var Folder|File $object */
     $object = BaseObject::loadById((int) $this->request->getQuery('objectId'), array('STORAGE'));
     if (!$object) {
         $this->errorCollection->addOne(new Error('Could not find file or folder', self::ERROR_COULD_NOT_FIND_FILE));
         $this->sendJsonErrorResponse();
     }
     $storage = $object->getStorage();
     $securityContext = $storage->getCurrentUserSecurityContext();
     if (!$object->canRead($securityContext)) {
         $this->errorCollection->addOne(new Error('Could not find file or folder', self::ERROR_COULD_NOT_READ_FILE));
         $this->sendJsonErrorResponse();
     }
     $gridOptions = new Internals\Grid\FolderListOptions($storage);
     $pageSize = $gridOptions->getPageSize();
     $parameters = array('select' => array('ID'), 'filter' => array('PARENT_ID' => $object->getParentId(), 'DELETED_TYPE' => ObjectTable::DELETED_TYPE_NONE), 'order' => $gridOptions->getOrderForOrm(), 'limit' => $pageSize);
     $countQuery = new Query(ObjectTable::getEntity());
     $countQuery->addSelect(new ExpressionField('CNT', 'COUNT(1)'));
     $countQuery->setFilter($parameters['filter']);
     $totalCount = $countQuery->setLimit(null)->setOffset(null)->exec()->fetch();
     $totalCount = $totalCount['CNT'];
     $pageCount = ceil($totalCount / $pageSize);
     $driver = Driver::getInstance();
     $finalPage = null;
     for ($pageNumber = 1; $pageNumber <= $pageCount; $pageNumber++) {
         $fullParameters = $driver->getRightsManager()->addRightsCheck($securityContext, $parameters, array('ID', 'CREATED_BY'));
         $fullParameters['offset'] = $pageSize * ($pageNumber - 1);
         $query = ObjectTable::getList($fullParameters);
         while ($row = $query->fetch()) {
             if ($row['ID'] == $object->getId()) {
                 $finalPage = $pageNumber;
                 break;
             }
         }
         if ($finalPage !== null) {
             break;
         }
     }
     $finalPage = $finalPage ?: 1;
     $command = $this->request->getQuery('cmd') ?: '';
     if ($command) {
         $command = '!' . $command;
     }
     LocalRedirect($driver->getUrlManager()->getPathInListing($object) . "?&pageNumber={$finalPage}#hl-" . $object->getId() . $command);
 }
Example #5
0
 /**
  * Deletes unnecessary files, which don't relate to version or object.
  *
  * @param int $portion Count of files which we want to delete. Default value is 10.
  * @return string
  */
 public static function deleteUnnecessaryFiles($portion = 10)
 {
     $query = new Query(FileTable::getEntity());
     $query->addSelect('ID')->addFilter('=EXTERNAL_ID', 'unnecessary')->addFilter('=MODULE_ID', Driver::INTERNAL_MODULE_ID)->setLimit($portion);
     $workLoad = false;
     $dbResult = $query->exec();
     while ($row = $dbResult->fetch()) {
         $workLoad = true;
         \CFile::delete($row['ID']);
     }
     if (!$workLoad) {
         return '';
     }
     return static::className() . '::deleteUnnecessaryFiles();';
 }
 /**
  * @return boolean
  */
 public static function isRegistered($ownerID)
 {
     if (!is_int($ownerID)) {
         $ownerID = (int) $ownerID;
     }
     if ($ownerID <= 0) {
         throw new Main\ArgumentException('Owner ID must be greater than zero.', 'ownerID');
     }
     $query = new Query(DealInvoiceStatisticsTable::getEntity());
     $query->addSelect('CREATED_DATE');
     $query->addFilter('=OWNER_ID', $ownerID);
     $query->setLimit(1);
     $dbResult = $query->exec();
     $result = $dbResult->fetch();
     return is_array($result);
 }
 public static function getMismatches($entityTypeID, $entityID, $typeID, $matchHash, $userID, $limit = 0)
 {
     if (!is_int($limit)) {
         $limit = (int) $limit;
     }
     $results = array();
     $query = new Main\Entity\Query(Entity\DuplicateIndexMismatchTable::getEntity());
     $query->addSelect('R_ENTITY_ID', 'ENTITY_ID');
     $query->addFilter('=USER_ID', $userID);
     $query->addFilter('=ENTITY_TYPE_ID', $entityTypeID);
     $query->addFilter('=TYPE_ID', $typeID);
     $query->addFilter('=MATCH_HASH', $matchHash);
     $query->addFilter('=L_ENTITY_ID', $entityID);
     if ($limit > 0) {
         $query->addOrder('R_ENTITY_ID', 'ASC');
         $query->setLimit($limit);
     }
     $dbResult = $query->exec();
     while ($fields = $dbResult->fetch()) {
         $results[] = (int) $fields['ENTITY_ID'];
     }
     $query = new Main\Entity\Query(Entity\DuplicateIndexMismatchTable::getEntity());
     $query->addSelect('L_ENTITY_ID', 'ENTITY_ID');
     $query->addFilter('=USER_ID', $userID);
     $query->addFilter('=ENTITY_TYPE_ID', $entityTypeID);
     $query->addFilter('=TYPE_ID', $typeID);
     $query->addFilter('=MATCH_HASH', $matchHash);
     $query->addFilter('=R_ENTITY_ID', $entityID);
     if ($limit > 0) {
         $query->addOrder('L_ENTITY_ID', 'ASC');
         $query->setLimit($limit);
     }
     $dbResult = $query->exec();
     while ($fields = $dbResult->fetch()) {
         $results[] = (int) $fields['ENTITY_ID'];
     }
     return $results;
 }
Example #8
0
 public static function getAllCounter()
 {
     $countQuery = new Main\Entity\Query(Sale\Internals\DiscountTable::getEntity());
     $countQuery->addSelect(new Main\Entity\ExpressionField('CNT', 'COUNT(1)'));
     $countQuery->setFilter(array('=VERSION' => Sale\Internals\DiscountTable::VERSION_NEW));
     $totalCount = $countQuery->setLimit(null)->setOffset(null)->exec()->fetch();
     return (int) $totalCount['CNT'];
 }
Example #9
0
 /**
  * @return Query
  */
 protected static function prepareInvoiceQuery($startDate, $endDate, $responsibleIDs = null, $groupByDate = true)
 {
     $query = new Query(DealInvoiceStatisticsTable::getEntity());
     $query->addSelect('OWNER_ID');
     $query->addFilter('=IS_LOST', false);
     $query->addFilter('>=CREATED_DATE', $startDate);
     $query->addFilter('<=CREATED_DATE', $endDate);
     $query->addGroup('OWNER_ID');
     if (is_array($responsibleIDs) && !empty($responsibleIDs)) {
         $query->addFilter('@RESPONSIBLE_ID', $responsibleIDs);
     }
     if ($groupByDate) {
         $query->addSelect('CREATED_DATE', 'DATE');
         $query->addGroup('CREATED_DATE');
         $query->addOrder('CREATED_DATE', 'ASC');
     }
     return $query;
 }
        $navyParams['SIZEN'] = (int) $navyParams['SIZEN'];
    }
}
if ($selectFields['PROPERTY_TYPE']) {
    $selectFields['USER_TYPE'] = true;
}
$selectFields = array_keys($selectFields);
$getListParams = array('select' => $selectFields, 'filter' => $arFilter, 'order' => $propertyOrder);
if ($usePageNavigation) {
    $getListParams['limit'] = $navyParams['SIZEN'];
    $getListParams['offset'] = $navyParams['SIZEN'] * ($navyParams['PAGEN'] - 1);
}
$totalPages = 0;
if ($usePageNavigation) {
    $countQuery = new Main\Entity\Query(Iblock\PropertyTable::getEntity());
    $countQuery->addSelect(new Main\Entity\ExpressionField('CNT', 'COUNT(1)'));
    $countQuery->setFilter($getListParams['filter']);
    $totalCount = $countQuery->setLimit(null)->setOffset(null)->exec()->fetch();
    unset($countQuery);
    $totalCount = (int) $totalCount['CNT'];
    if ($totalCount > 0) {
        $totalPages = ceil($totalCount / $navyParams['SIZEN']);
        if ($navyParams['PAGEN'] > $totalPages) {
            $navyParams['PAGEN'] = $totalPages;
        }
        $getListParams['limit'] = $navyParams['SIZEN'];
        $getListParams['offset'] = $navyParams['SIZEN'] * ($navyParams['PAGEN'] - 1);
    } else {
        $navyParams['PAGEN'] = 1;
        $getListParams['limit'] = $navyParams['SIZEN'];
        $getListParams['offset'] = 0;
Example #11
0
 protected function getFilterCswFields(&$filter)
 {
     $fields = array();
     foreach ($filter as $filter_def => &$filter_match) {
         if ($filter_def === 'LOGIC') {
             continue;
         }
         if (!is_numeric($filter_def)) {
             $csw_result = \CSQLWhere::makeOperation($filter_def);
             list($definition, ) = array_values($csw_result);
             $chain = $this->filter_chains[$definition];
             $last = $chain->getLastElement();
             // need to create an alternative of CSQLWhere in D7.Entity
             $field_type = $last->getValue()->getDataType();
             // rewrite type & value for CSQLWhere
             if ($field_type == 'integer') {
                 $field_type = 'int';
             } elseif ($field_type == 'boolean') {
                 $field_type = 'string';
                 /** @var BooleanField $field */
                 $field = $last->getValue();
                 $values = $field->getValues();
                 if (is_numeric($values[0]) && is_numeric($values[1])) {
                     $field_type = 'int';
                 }
                 if (is_scalar($filter_match)) {
                     $filter_match = $field->normalizeValue($filter_match);
                 }
             } elseif ($field_type == 'float') {
                 $field_type = 'double';
             } elseif ($field_type == 'enum' || $field_type == 'text') {
                 $field_type = 'string';
             }
             $sqlDefinition = $chain->getSqlDefinition();
             $callback = null;
             // data-doubling-off mode
             /** @see disableDataDoubling */
             if ($chain->forcesDataDoublingOff() || $this->data_doubling_off && $chain->hasBackReference()) {
                 $primaryName = $this->init_entity->getPrimary();
                 $uniquePostfix = '_TMP' . rand();
                 // build subquery
                 $subQuery = new Query($this->init_entity);
                 $subQuery->addSelect($primaryName);
                 $subQuery->addFilter($filter_def, $filter_match);
                 $subQuery->setTableAliasPostfix(strtolower($uniquePostfix));
                 $subQuerySql = $subQuery->getQuery();
                 // proxying subquery as value to callback
                 $filter_match = $subQuerySql;
                 $callback = array($this, 'dataDoublingCallback');
                 $field_type = 'callback';
                 // change sql definition
                 $idChain = $this->getRegisteredChain($primaryName);
                 $sqlDefinition = $idChain->getSqlDefinition();
             }
             //$is_having = $last->getValue() instanceof ExpressionField && $last->getValue()->isAggregated();
             // if back-reference found (Entity:REF)
             // if NO_DOUBLING mode enabled, then change getSQLDefinition to subquery exists(...)
             // and those chains should not be in joins if it is possible
             /*if (!$this->data_doubling && $chain->hasBackReference())
             				{
             					$field_type = 'callback';
             					$init_query = $this;
             
             					$callback = function ($field, $operation, $value) use ($init_query, $chain)
             					{
             						$init_entity = $init_query->getEntity();
             						$init_table_alias = CBaseEntity::camel2snake($init_entity->getName()).$init_query->getTableAliasPostfix();
             
             						$filter = array();
             
             						// add primary linking with main query
             						foreach ($init_entity->getPrimaryArray() as $primary)
             						{
             							$filter['='.$primary] = new CSQLWhereExpression('?#', $init_table_alias.'.'.$primary);
             						}
             
             						// add value filter
             						$filter[CSQLWhere::getOperationByCode($operation).$chain->getDefinition()] = $value;
             
             						// build subquery
             						$query_class = __CLASS__;
             						$sub_query = new $query_class($init_entity);
             						$sub_query->setFilter($filter);
             						$sub_query->setTableAliasPostfix('_sub');
             
             						return 'EXISTS(' . $sub_query->getQuery() . ')';
             					};
             				}*/
             $fields[$definition] = array('TABLE_ALIAS' => 'table', 'FIELD_NAME' => $sqlDefinition, 'FIELD_TYPE' => $field_type, 'MULTIPLE' => '', 'JOIN' => '', 'CALLBACK' => $callback);
         }
         if (is_array($filter_match)) {
             $fields = array_merge($fields, $this->getFilterCswFields($filter_match));
         }
     }
     return $fields;
 }
 /** @return array */
 public function prepareEntityListFilter(array $filterParams)
 {
     $filter = self::internalizeFilter($filterParams);
     $query = new Query(DealActivityStatisticsTable::getEntity());
     $query->addSelect('OWNER_ID');
     $query->addGroup('OWNER_ID');
     $period = $filter->getPeriod();
     $periodStartDate = $period['START'];
     $periodEndDate = $period['END'];
     $query->addFilter('>=DEADLINE_DATE', $periodStartDate);
     $query->addFilter('<=DEADLINE_DATE', $periodEndDate);
     $responsibleIDs = $filter->getResponsibleIDs();
     if (!empty($responsibleIDs)) {
         $query->addFilter('@RESPONSIBLE_ID', $responsibleIDs);
     }
     $semanticID = $filter->getExtraParam('semanticID', PhaseSemantics::UNDEFINED);
     if ($semanticID !== PhaseSemantics::UNDEFINED) {
         $query->addFilter('=STAGE_SEMANTIC_ID', $semanticID);
     }
     $field = isset($filterParams['FIELD']) ? $filterParams['FIELD'] : '';
     if ($field === 'CALL_QTY' || $field === 'MEETING_QTY' || $field === 'EMAIL_QTY') {
         $query->addFilter(">{$field}", 0);
     } elseif ($field === 'TOTAL') {
         $query->registerRuntimeField(null, new ExpressionField('TOTAL', '(%s + %s + %s)', array('CALL_QTY', 'MEETING_QTY', 'EMAIL_QTY')));
         $query->addFilter('>TOTAL', 0);
     }
     return array('__JOINS' => array(array('TYPE' => 'INNER', 'SQL' => 'INNER JOIN(' . $query->getQuery() . ') DS ON DS.OWNER_ID = L.ID')));
 }
 public static function getRegisteredCodes($entityTypeID, $entityID, $enablePermissionCheck = false, $userID = 0, $limit = 50)
 {
     if (!is_int($entityTypeID)) {
         throw new Main\ArgumentTypeException('entityTypeID', 'integer');
     }
     if (!is_int($entityID)) {
         throw new Main\ArgumentTypeException('entityID', 'integer');
     }
     if (!is_int($userID)) {
         throw new Main\ArgumentTypeException('userID', 'integer');
     }
     if (!is_bool($enablePermissionCheck)) {
         throw new Main\ArgumentTypeException('enablePermissionCheck', 'boolean');
     }
     if (!is_int($limit)) {
         throw new Main\ArgumentTypeException('limit', 'integer');
     }
     $query = new Main\Entity\Query(DuplicateCommunicationMatchCodeTable::getEntity());
     $query->addSelect('TYPE');
     $query->addSelect('VALUE');
     $query->addFilter('=ENTITY_TYPE_ID', $entityTypeID);
     $query->addFilter('=ENTITY_ID', $entityID);
     if ($enablePermissionCheck && $userID > 0) {
         $permissions = isset($params['PERMISSIONS']) ? $params['PERMISSIONS'] : null;
         if ($permissions === null) {
             $permissions = \CCrmPerms::GetUserPermissions($userID);
         }
         $permissionSql = \CCrmPerms::BuildSql(\CCrmOwnerType::ResolveName($entityTypeID), '', 'READ', array('RAW_QUERY' => true, 'PERMS' => $permissions));
         if ($permissionSql === false) {
             //Access denied;
             return array();
         } elseif ($permissionSql !== '') {
             $query->addFilter('@ENTITY_ID', new Main\DB\SqlExpression($permissionSql));
         }
     }
     if ($limit > 0) {
         $query->setLimit($limit);
     }
     $dbResult = $query->exec();
     $results = array();
     while ($fields = $dbResult->fetch()) {
         $type = isset($fields['TYPE']) ? $fields['TYPE'] : '';
         $value = isset($fields['VALUE']) ? $fields['VALUE'] : '';
         if (!isset($results[$type])) {
             $results[$type] = array();
         }
         $results[$type][] = $value;
     }
     return $results;
 }
Example #14
0
 /**
  * @return Query
  */
 protected static function prepareInvoiceQuery($startDate, $endDate, $groupByDate = true)
 {
     $query = new Query(DealInvoiceStatisticsTable::getEntity());
     $query->addSelect('OWNER_ID');
     $query->addFilter('=IS_LOST', false);
     $query->addFilter('>=CREATED_DATE', $startDate);
     $query->addFilter('<=CREATED_DATE', $endDate);
     $query->addGroup('OWNER_ID');
     if ($groupByDate) {
         $query->addSelect('CREATED_DATE', 'DATE');
         $query->addGroup('CREATED_DATE');
         $query->addOrder('CREATED_DATE', 'ASC');
     }
     return $query;
 }
 /**
  * Load conversion map
  * @static
  * @param int $srcEntityTypeID Source Entity Type ID
  * @param int $dstEntityTypeID Destination Entity Type ID
  * @return EntityConversionMap
  */
 public static function load($srcEntityTypeID, $dstEntityTypeID)
 {
     $query = new Query(EntityConversionMapTable::getEntity());
     $query->addSelect('DATA');
     $query->addFilter('=SRC_TYPE_ID', $srcEntityTypeID);
     $query->addFilter('=DST_TYPE_ID', $dstEntityTypeID);
     $dbResult = $query->exec();
     $result = $dbResult->fetch();
     if (!is_array($result)) {
         return null;
     }
     $params = isset($result['DATA']) ? unserialize($result['DATA']) : null;
     if (!is_array($params)) {
         return null;
     }
     $item = new EntityConversionMap();
     $item->internalize($params);
     return $item;
 }
 protected function getRootEntityID($matchHash)
 {
     $query = new Main\Entity\Query(Entity\DuplicateIndexTable::getEntity());
     $query->addSelect('ROOT_ENTITY_ID');
     $query->addFilter('=USER_ID', $this->getUserID());
     $query->addFilter('=ENTITY_TYPE_ID', $this->getEntityTypeID());
     $query->addFilter('=TYPE_ID', $this->typeID);
     $query->addFilter('=MATCH_HASH', $matchHash);
     $fields = $query->exec()->fetch();
     return is_array($fields) ? (int) $fields['ROOT_ENTITY_ID'] : 0;
 }
    if ($navyParams['SHOW_ALL']) {
        $usePageNavigation = false;
    } else {
        $navyParams['PAGEN'] = (int) $navyParams['PAGEN'];
        $navyParams['SIZEN'] = (int) $navyParams['SIZEN'];
    }
}
$getListParams = array('select' => $lAdmin->GetVisibleHeaderColumns(), 'filter' => $filterValues, 'order' => array($by => $order));
unset($filterValues);
if ($usePageNavigation) {
    $getListParams['limit'] = $navyParams['SIZEN'];
    $getListParams['offset'] = $navyParams['SIZEN'] * ($navyParams['PAGEN'] - 1);
}
if ($usePageNavigation) {
    $countQuery = new Query($entity_data_class::getEntity());
    $countQuery->addSelect(new ExpressionField('CNT', 'COUNT(1)'));
    $countQuery->setFilter($getListParams['filter']);
    $totalCount = $countQuery->setLimit(null)->setOffset(null)->exec()->fetch();
    unset($countQuery);
    $totalCount = (int) $totalCount['CNT'];
    if ($totalCount > 0) {
        $totalPages = ceil($totalCount / $navyParams['SIZEN']);
        if ($navyParams['PAGEN'] > $totalPages) {
            $navyParams['PAGEN'] = $totalPages;
        }
        $getListParams['limit'] = $navyParams['SIZEN'];
        $getListParams['offset'] = $navyParams['SIZEN'] * ($navyParams['PAGEN'] - 1);
    } else {
        $navyParams['PAGEN'] = 1;
        $getListParams['limit'] = $navyParams['SIZEN'];
        $getListParams['offset'] = 0;
 /**
  * @return DedupeDataSourceResult
  */
 public function getList($offset, $limit)
 {
     $result = new DedupeDataSourceResult();
     $typeID = $this->typeID;
     $entityTypeID = $this->getEntityTypeID();
     $enablePermissionCheck = $this->isPermissionCheckEnabled();
     //$userID = $this->getUserID();
     $query = new Main\Entity\Query(Entity\DuplicateEntityMatchHashTable::getEntity());
     $query->addSelect('MATCH_HASH');
     $query->addGroup('MATCH_HASH');
     $query->addOrder('MATCH_HASH', 'ASC');
     $query->registerRuntimeField('', new Main\Entity\ExpressionField('QTY', 'COUNT(*)'));
     $query->addSelect('QTY');
     $query->addFilter('>QTY', 1);
     $query->addFilter('=ENTITY_TYPE_ID', $entityTypeID);
     $query->addFilter('=TYPE_ID', $typeID);
     $permissionSql = '';
     if ($enablePermissionCheck) {
         $permissionSql = $this->preparePermissionSql();
         if ($permissionSql === false) {
             //Access denied;
             return $result;
         }
         if ($permissionSql !== '') {
             $query->addFilter('@ENTITY_ID', new Main\DB\SqlExpression($permissionSql));
         }
     }
     if (!is_int($offset)) {
         $offset = (int) $offset;
     }
     if ($offset > 0) {
         $query->setOffset($offset);
     }
     if (!is_int($limit)) {
         $limit = (int) $limit;
     }
     if ($limit > 0) {
         $query->setLimit($limit);
     }
     $dbResult = $query->exec();
     $processedItemCount = 0;
     $lightHashes = array();
     $heavyHashes = array();
     while ($fields = $dbResult->fetch()) {
         $processedItemCount++;
         $quantity = isset($fields['QTY']) ? (int) $fields['QTY'] : 0;
         $matchHash = isset($fields['MATCH_HASH']) ? $fields['MATCH_HASH'] : '';
         if ($matchHash === '' || $quantity < 2) {
             continue;
         }
         if ($quantity <= 100) {
             $lightHashes[] = $matchHash;
         } else {
             $heavyHashes[] = $matchHash;
         }
     }
     $result->setProcessedItemCount($processedItemCount);
     $map = array();
     if (!empty($heavyHashes)) {
         foreach ($heavyHashes as $matchHash) {
             $query = new Main\Entity\Query(Entity\DuplicateEntityMatchHashTable::getEntity());
             $query->addSelect('ENTITY_ID');
             $query->addSelect('IS_PRIMARY');
             $query->addFilter('=ENTITY_TYPE_ID', $entityTypeID);
             $query->addFilter('=TYPE_ID', $typeID);
             $query->addFilter('=MATCH_HASH', $matchHash);
             if ($enablePermissionCheck && $permissionSql !== '') {
                 $query->addFilter('@ENTITY_ID', new Main\DB\SqlExpression($permissionSql));
             }
             $query->setOffset(0);
             $query->setLimit(100);
             $dbResult = $query->exec();
             while ($fields = $dbResult->fetch()) {
                 $entityID = isset($fields['ENTITY_ID']) ? (int) $fields['ENTITY_ID'] : 0;
                 if ($entityID <= 0) {
                     continue;
                 }
                 if (!isset($map[$matchHash])) {
                     $map[$matchHash] = array();
                 }
                 $isPrimary = isset($fields['IS_PRIMARY']) && $fields['IS_PRIMARY'] === 'Y';
                 if ($isPrimary) {
                     if (!isset($map[$matchHash]['PRIMARY'])) {
                         $map[$matchHash]['PRIMARY'] = array();
                     }
                     $map[$matchHash]['PRIMARY'][] = $entityID;
                 } else {
                     if (!isset($map[$matchHash]['SECONDARY'])) {
                         $map[$matchHash]['SECONDARY'] = array();
                     }
                     $map[$matchHash]['SECONDARY'][] = $entityID;
                 }
             }
         }
     }
     if (!empty($lightHashes)) {
         $query = new Main\Entity\Query(Entity\DuplicateEntityMatchHashTable::getEntity());
         $query->addSelect('ENTITY_ID');
         $query->addSelect('MATCH_HASH');
         $query->addSelect('IS_PRIMARY');
         $query->addFilter('=ENTITY_TYPE_ID', $entityTypeID);
         $query->addFilter('=TYPE_ID', $typeID);
         $query->addFilter('@MATCH_HASH', $lightHashes);
         if ($enablePermissionCheck && $permissionSql !== '') {
             $query->addFilter('@ENTITY_ID', new Main\DB\SqlExpression($permissionSql));
         }
         $dbResult = $query->exec();
         while ($fields = $dbResult->fetch()) {
             $entityID = isset($fields['ENTITY_ID']) ? (int) $fields['ENTITY_ID'] : 0;
             if ($entityID <= 0) {
                 continue;
             }
             $matchHash = isset($fields['MATCH_HASH']) ? $fields['MATCH_HASH'] : '';
             if ($matchHash === '') {
                 continue;
             }
             if (!isset($map[$matchHash])) {
                 $map[$matchHash] = array();
             }
             $isPrimary = isset($fields['IS_PRIMARY']) && $fields['IS_PRIMARY'] === 'Y';
             if ($isPrimary) {
                 if (!isset($map[$matchHash]['PRIMARY'])) {
                     $map[$matchHash]['PRIMARY'] = array();
                 }
                 $map[$matchHash]['PRIMARY'][] = $entityID;
             } else {
                 if (!isset($map[$matchHash]['SECONDARY'])) {
                     $map[$matchHash]['SECONDARY'] = array();
                 }
                 $map[$matchHash]['SECONDARY'][] = $entityID;
             }
         }
     }
     $this->prepareResult($map, $result);
     return $result;
 }
 /**
  * @return boolean
  */
 public static function synchronize($ownerID, array $entityFields = null)
 {
     if (!is_int($ownerID)) {
         $ownerID = (int) $ownerID;
     }
     if ($ownerID <= 0) {
         throw new Main\ArgumentException('Owner ID must be greater than zero.', 'ownerID');
     }
     $query = new Query(DealActivityStatisticsTable::getEntity());
     $query->addSelect('RESPONSIBLE_ID');
     $query->addFilter('=OWNER_ID', $ownerID);
     $query->setLimit(1);
     $dbResult = $query->exec();
     $first = $dbResult->fetch();
     if (!is_array($first)) {
         return false;
     }
     if (!is_array($entityFields)) {
         $dbResult = \CCrmDeal::GetListEx(array(), array('=ID' => $ownerID, 'CHECK_PERMISSIONS' => 'N'), false, false, array('ASSIGNED_BY_ID'));
         $entityFields = is_object($dbResult) ? $dbResult->Fetch() : null;
         if (!is_array($entityFields)) {
             return false;
         }
     }
     $responsibleID = isset($entityFields['ASSIGNED_BY_ID']) ? (int) $entityFields['ASSIGNED_BY_ID'] : 0;
     if ($responsibleID === (int) $first['RESPONSIBLE_ID']) {
         return false;
     }
     DealActivityStatisticsTable::synchronize($ownerID, array('RESPONSIBLE_ID' => $responsibleID));
     return true;
 }
Example #20
0
 /**
  * @return Main\Entity\Query
  */
 private function createQuery($offset = 0, $limit = 0)
 {
     if (!is_int($offset)) {
         $offset = intval($offset);
     }
     if (!is_int($limit)) {
         $limit = intval($limit);
     }
     $typeIDs = $this->getTypeIDs();
     if (empty($typeIDs)) {
         throw new Main\NotSupportedException("Criterion types are required.");
     }
     $query = new Main\Entity\Query(Entity\DuplicateIndexTable::getEntity());
     $query->addSelect('ROOT_ENTITY_ID');
     $query->addSelect('ROOT_ENTITY_NAME');
     $query->addSelect('ROOT_ENTITY_TITLE');
     $query->addSelect('QUANTITY');
     $query->addSelect('TYPE_ID');
     $query->addSelect('MATCHES');
     $query->addSelect('IS_JUNK');
     $permissionSql = '';
     if ($this->enablePermissionCheck) {
         $permissions = \CCrmPerms::GetUserPermissions($this->userID);
         $permissionSql = \CCrmPerms::BuildSql(\CCrmOwnerType::ResolveName($this->entityTypeID), '', 'READ', array('RAW_QUERY' => true, 'PERMS' => $permissions));
         if ($permissionSql === false) {
             //Access denied;
             return null;
         }
     }
     $query->addFilter('=USER_ID', $this->userID);
     $query->addFilter('=ENTITY_TYPE_ID', $this->entityTypeID);
     $query->addFilter('@TYPE_ID', $typeIDs);
     if ($this->enablePermissionCheck && $permissionSql !== '') {
         $query->addFilter('@ROOT_ENTITY_ID', new Main\DB\SqlExpression($permissionSql));
     }
     if ($offset > 0) {
         $query->setOffset($offset);
     }
     if ($limit > 0) {
         $query->setLimit($limit);
     }
     $enableSorting = $this->sortTypeID !== DuplicateIndexType::UNDEFINED;
     if ($enableSorting) {
         $order = $this->sortOrder === SORT_DESC ? 'DESC' : 'ASC';
         if ($this->sortTypeID === DuplicateIndexType::COMMUNICATION_EMAIL) {
             $query->addOrder('ROOT_ENTITY_EMAIL_FLAG', $order);
             $query->addOrder('ROOT_ENTITY_EMAIL', $order);
         } elseif ($this->sortTypeID === DuplicateIndexType::COMMUNICATION_PHONE) {
             $query->addOrder('ROOT_ENTITY_PHONE_FLAG', $order);
             $query->addOrder('ROOT_ENTITY_PHONE', $order);
         } elseif ($this->sortTypeID === DuplicateIndexType::PERSON) {
             $query->addOrder('ROOT_ENTITY_NAME_FLAG', $order);
             $query->addOrder('ROOT_ENTITY_NAME', $order);
         } elseif ($this->sortTypeID === DuplicateIndexType::ORGANIZATION) {
             $query->addOrder('ROOT_ENTITY_TITLE_FLAG', $order);
             $query->addOrder('ROOT_ENTITY_TITLE', $order);
         }
     }
     return $query;
 }
Example #21
0
 protected static function getHourlyCompanyActivitySince(Type\DateTime $hour = null)
 {
     $query = new Entity\Query('Bitrix\\Intranet\\UStat\\UserHourTable');
     // set all activity columns
     $uStatFields = UserHourTable::getEntity()->getFields();
     foreach ($uStatFields as $uStatField) {
         if ($uStatField instanceof Entity\ScalarField && !$uStatField->isPrimary()) {
             $query->addSelect(new Entity\ExpressionField($uStatField->getName() . '_SUM', 'SUM(%s)', $uStatField->getName()));
         }
     }
     // add & automatically group by hour
     $query->addSelect('HOUR');
     // add filter by date
     if ($hour !== null) {
         $query->setFilter(array('>=HOUR' => \ConvertTimeStamp($hour->getTimestamp(), 'FULL')));
     }
     // collect activity
     $activity = array();
     $result = $query->exec();
     while ($row = $result->fetch()) {
         foreach ($row as $k => $v) {
             if (substr($k, -4) === '_SUM') {
                 $row[substr($k, 0, -4)] = $v;
                 unset($row[$k]);
             }
         }
         $activity[] = $row;
     }
     return $activity;
 }
 public static function loadEntitiesMatches($entityTypeID, array $entityIDs)
 {
     $query = new Main\Entity\Query(DuplicateOrganizationMatchCodeTable::getEntity());
     $query->addFilter('=ENTITY_TYPE_ID', $entityTypeID);
     $query->addFilter('@ENTITY_ID', $entityIDs);
     $query->addSelect('ENTITY_ID');
     $query->addSelect('TITLE');
     $dbResult = $query->exec();
     $results = array();
     while ($fields = $dbResult->fetch()) {
         $entityID = isset($fields['ENTITY_ID']) ? (int) $fields['ENTITY_ID'] : 0;
         if ($entityID <= 0) {
             continue;
         }
         $results[$entityID] = array('TITLE' => isset($fields['TITLE']) ? $fields['TITLE'] : '');
     }
     return $results;
 }
 public static function synchronize($ownerID, array $entityFields = null)
 {
     if (!is_int($ownerID)) {
         $ownerID = (int) $ownerID;
     }
     if ($ownerID <= 0) {
         throw new Main\ArgumentException('Owner ID must be greater than zero.', 'ownerID');
     }
     $query = new Query(DealStageHistoryTable::getEntity());
     $query->addSelect('START_DATE');
     $query->addSelect('END_DATE');
     $query->addSelect('RESPONSIBLE_ID');
     $query->addFilter('=OWNER_ID', $ownerID);
     $query->setLimit(1);
     $dbResult = $query->exec();
     $first = $dbResult->fetch();
     if (!is_array($first)) {
         return false;
     }
     if (!is_array($entityFields)) {
         $dbResult = \CCrmDeal::GetListEx(array(), array('=ID' => $ownerID, 'CHECK_PERMISSIONS' => 'N'), false, false, array('ASSIGNED_BY_ID', 'BEGINDATE', 'CLOSEDATE'));
         $entityFields = is_object($dbResult) ? $dbResult->Fetch() : null;
         if (!is_array($entityFields)) {
             return false;
         }
     }
     $responsibleID = isset($entityFields['ASSIGNED_BY_ID']) ? (int) $entityFields['ASSIGNED_BY_ID'] : 0;
     $beginDate = isset($entityFields['BEGINDATE']) ? $entityFields['BEGINDATE'] : '';
     /** @var Date $startDate */
     $startDate = new Date($beginDate);
     $closeDate = isset($entityFields['CLOSEDATE']) ? $entityFields['CLOSEDATE'] : '';
     /** @var Date $endDate */
     $endDate = $closeDate !== '' ? new Date($closeDate) : new Date('9999-12-31', 'Y-m-d');
     if ($startDate->getTimestamp() === $first['START_DATE']->getTimestamp() && $endDate->getTimestamp() === $first['END_DATE']->getTimestamp() && $responsibleID === (int) $first['RESPONSIBLE_ID']) {
         return false;
     }
     DealStageHistoryTable::synchronize($ownerID, array('START_DATE' => $startDate, 'END_DATE' => $endDate, 'RESPONSIBLE_ID' => $responsibleID));
     return true;
 }
Example #24
0
 private function getListUsers(array $filter)
 {
     $limit = !isset($this->params['limit']) ? self::USERS_ON_PAGE : (int) $this->params['limit'];
     $page = empty($this->params['page']) ? 1 : (int) $this->params['page'];
     $offset = ($page - 1) * $limit;
     $query = \Bitrix\Webdav\FolderInviteTable::getList(array('select' => array('*', 'INVITE_USER'), 'filter' => $filter, 'limit' => $limit, 'offset' => $offset, 'order' => array('ID' => 'ASC')));
     $users = array();
     while ($row = $query->fetch()) {
         $row = $this->reformatInviteRow($row);
         $users[] = $row;
     }
     $countQuery = new Query(\Bitrix\Webdav\FolderInviteTable::getEntity());
     $countQuery->addSelect(new ExpressionField('CNT', 'COUNT(1)'));
     $countQuery->setFilter($filter);
     $totalCount = $countQuery->setLimit(null)->setOffset(null)->exec()->fetch();
     $totalCount = $totalCount['CNT'];
     return array('USERS' => $users, 'COUNT' => count($users), 'PAGE' => $page, 'ON_PAGE' => self::USERS_ON_PAGE, 'TOTAL_COUNT' => intval($totalCount), 'TOTAL_PAGE' => ceil($totalCount / $limit));
 }
Example #25
0
 /** @return array */
 public function prepareEntityListFilter(array $filterParams)
 {
     $filter = self::internalizeFilter($filterParams);
     $query = new Query(DealStageHistoryTable::getEntity());
     $query->addSelect('OWNER_ID');
     $query->addGroup('OWNER_ID');
     $period = $filter->getPeriod();
     $periodStartDate = $period['START'];
     $periodEndDate = $period['END'];
     $query->addFilter('=TYPE_ID', HistoryEntryType::CREATION);
     $query->addFilter('>=START_DATE', $periodStartDate);
     $query->addFilter('<=START_DATE', $periodEndDate);
     $query->registerRuntimeField('', new ExpressionField('E1', '(CASE WHEN NOT EXISTS(' . self::prepareHistoryQuery($periodStartDate, $periodEndDate, HistoryEntryType::MODIFICATION, '%s', '_i')->getQuery() . ') THEN 1 ELSE 0 END)', 'OWNER_ID'));
     $query->addFilter('=E1', 1);
     $query->registerRuntimeField('', new ExpressionField('E2', '(CASE WHEN NOT EXISTS(' . self::prepareHistoryQuery($periodStartDate, $periodEndDate, HistoryEntryType::FINALIZATION, '%s', '_i')->getQuery() . ') THEN 1 ELSE 0 END)', 'OWNER_ID'));
     $query->addFilter('=E2', 1);
     $query->registerRuntimeField('', new ExpressionField('E3', '(CASE WHEN NOT EXISTS(' . self::prepareActivityQuery($periodStartDate, $periodEndDate, '%s')->getQuery() . ') THEN 1 ELSE 0 END)', 'OWNER_ID'));
     $query->addFilter('=E3', 1);
     $query->registerRuntimeField('', new ExpressionField('E4', '(CASE WHEN NOT EXISTS(' . self::prepareInvoiceQuery($periodStartDate, $periodEndDate, '%s')->getQuery() . ') THEN 1 ELSE 0 END)', 'OWNER_ID'));
     $query->addFilter('=E4', 1);
     $responsibleIDs = $filter->getResponsibleIDs();
     if (!empty($responsibleIDs)) {
         $query->addFilter('@RESPONSIBLE_ID', $responsibleIDs);
     }
     return array('__JOINS' => array(array('TYPE' => 'INNER', 'SQL' => 'INNER JOIN(' . $query->getQuery() . ') DS ON DS.OWNER_ID = L.ID')));
 }
Example #26
0
 /**
  * @param                     $elem
  * @param                     $select
  * @param                     $is_init_entity_aggregated
  * @param                     $fList
  * @param Entity\QueryChain[] $fChainList
  * @param                     $helper_class
  * @param Entity\Base         $entity
  *
  * @return array
  */
 public static function prepareSelectViewElement($elem, $select, $is_init_entity_aggregated, $fList, $fChainList, $helper_class, Entity\Base $entity)
 {
     $result = null;
     $alias = null;
     if (empty($elem['aggr']) && !strlen($elem['prcnt'])) {
         $result = $elem['name'];
     } else {
         $expression = '';
         /** @var Entity\Field $field */
         $field = $fList[$elem['name']];
         $chain = $fChainList[$elem['name']];
         $alias = $chain->getAlias();
         $dataType = call_user_func(array($helper_class, 'getFieldDataType'), $field);
         if (!empty($elem['aggr'])) {
             $alias = $elem['aggr'] . '_' . $alias;
             if ($dataType == 'boolean') {
                 // sum int for boolean
                 global $DB;
                 /** @var Entity\BooleanField $field */
                 $trueValue = $field->normalizeValue(true);
                 $localDef = 'CASE WHEN %s = \'' . $DB->ForSql($trueValue) . '\' THEN 1 ELSE 0 END';
             } else {
                 $localDef = '%s';
             }
             if ($elem['aggr'] == 'COUNT_DISTINCT') {
                 $dataType = 'integer';
                 $expression = array('COUNT(DISTINCT ' . $localDef . ')', $elem['name']);
             } else {
                 if ($dataType == 'boolean') {
                     $dataType = 'integer';
                 }
                 if ($elem['aggr'] == 'GROUP_CONCAT') {
                     $expression = array($localDef, $elem['name']);
                 } else {
                     $expression = array($elem['aggr'] . '(' . $localDef . ')', $elem['name']);
                 }
             }
             // pack 1:N aggregations into subquery
             if ($chain->hasBackReference() && $elem['aggr'] != 'GROUP_CONCAT') {
                 $confirm = call_user_func_array(array($helper_class, 'confirmSelectBackReferenceRewrite'), array(&$elem, $chain));
                 if ($confirm) {
                     $filter = array();
                     foreach ($entity->GetPrimaryArray() as $primary) {
                         $filter['=' . $primary] = new CSQLWhereExpression('?#', ToLower($entity->getCode()) . '.' . $primary);
                     }
                     $query = new Entity\Query($entity);
                     $query->addSelect(new Entity\ExpressionField('X', $expression[0], $elem['name']));
                     $query->setFilter($filter);
                     $query->setTableAliasPostfix('_sub');
                     $expression = array('(' . $query->getQuery() . ')');
                     // double aggregation if init entity aggregated
                     if ($is_init_entity_aggregated) {
                         if ($elem['aggr'] == 'COUNT_DISTINCT') {
                             $expression[0] = 'SUM(' . $expression[0] . ')';
                         } else {
                             $expression[0] = $elem['aggr'] . '(' . $expression[0] . ')';
                         }
                     }
                 }
                 // confirmed
             }
         }
         if (strlen($elem['prcnt'])) {
             $alias = $alias . '_PRCNT';
             $dataType = 'integer';
             if ($elem['prcnt'] == 'self_column') {
                 if (empty($expression)) {
                     $expression = array('%s', $elem['name']);
                 }
             } else {
                 if (empty($expression)) {
                     $localDef = '%s';
                     $localMembers = array($elem['name']);
                 } else {
                     $localDef = $expression[0];
                     $localMembers = array_slice($expression, 1);
                 }
                 list($remoteAlias, $remoteSelect) = self::prepareSelectViewElement($select[$elem['prcnt']], $select, $is_init_entity_aggregated, $fList, $fChainList, $helper_class, $entity);
                 if (is_array($remoteSelect) && !empty($remoteSelect['expression'])) {
                     // remote field is expression
                     $remoteDef = $remoteSelect['expression'][0];
                     $remoteMembers = array_slice($remoteSelect['expression'], 1);
                     $alias = $alias . '_FROM_' . $remoteAlias;
                 } else {
                     // remote field is usual field
                     $remoteDef = '%s';
                     $remoteMembers = array($remoteSelect);
                     $remoteAlias = Entity\QueryChain::getAliasByDefinition($entity, $remoteSelect);
                     $alias = $alias . '_FROM_' . $remoteAlias;
                 }
                 $exprDef = '(' . $localDef . ') / (' . $remoteDef . ') * 100';
                 $expression = array_merge(array($exprDef), $localMembers, $remoteMembers);
                 // 'ROUND(STATUS / ID * 100)'
                 // 'ROUND( (EX1(F1, F2)) / (EX2(F3, F1)) * 100)',
                 // F1, F2, F3, F1
             }
         }
         $result = array('data_type' => $dataType, 'expression' => $expression);
     }
     return array($alias, $result);
 }
 /** @return array */
 public function prepareEntityListFilter(array $filterParams)
 {
     $filter = self::internalizeFilter($filterParams);
     $query = new Query(DealInvoiceStatisticsTable::getEntity());
     $query->addSelect('OWNER_ID');
     $query->addGroup('OWNER_ID');
     $period = $filter->getPeriod();
     $periodStartDate = $period['START'];
     $periodEndDate = $period['END'];
     $query->addFilter('>=END_DATE', $periodStartDate);
     $query->addFilter('<=START_DATE', $periodEndDate);
     $responsibleIDs = $filter->getResponsibleIDs();
     if (!empty($responsibleIDs)) {
         $query->addFilter('@RESPONSIBLE_ID', $responsibleIDs);
     }
     $semanticID = $filter->getExtraParam('semanticID', PhaseSemantics::UNDEFINED);
     if ($semanticID !== PhaseSemantics::UNDEFINED) {
         $query->addFilter('=STAGE_SEMANTIC_ID', $semanticID);
     }
     return array('__JOINS' => array(array('TYPE' => 'INNER', 'SQL' => 'INNER JOIN(' . $query->getQuery() . ') DS ON DS.OWNER_ID = L.ID')));
 }
 protected function onAfterDuplicateCreated(Duplicate $dup, $entityTypeID, $userID, $enablePermissionCheck, $enableRanking, array &$rankings)
 {
     $name = $this->name;
     $lastName = $this->lastName;
     $secondName = $this->secondName;
     $rootEntityID = $dup->getRootEntityID();
     if ($secondName === '' && $name === '') {
         return;
     }
     $permissionSql = '';
     if ($enablePermissionCheck) {
         $permissions = isset($params['PERMISSIONS']) ? $params['PERMISSIONS'] : null;
         if ($permissions === null) {
             $permissions = \CCrmPerms::GetUserPermissions($userID);
         }
         $permissionSql = \CCrmPerms::BuildSql(\CCrmOwnerType::ResolveName($entityTypeID), '', 'READ', array('RAW_QUERY' => true, 'PERMS' => $permissions));
         if ($permissionSql === false) {
             //Access denied;
             return;
         }
     }
     if ($secondName !== '') {
         $query = new Main\Entity\Query(DuplicatePersonMatchCodeTable::getEntity());
         $query->addSelect('ENTITY_ID');
         $query->addFilter('=ENTITY_TYPE_ID', $entityTypeID);
         $query->addFilter('=LAST_NAME', $lastName);
         $query->addFilter('=NAME', $name);
         $query->addFilter('=SECOND_NAME', '');
         if ($rootEntityID) {
             $query->addFilter('!ENTITY_ID', $rootEntityID);
             $query->addFilter('!@ENTITY_ID', DuplicateIndexMismatch::prepareQueryField(self::createFromMatches(array('LAST_NAME' => $lastName, 'NAME' => $name)), $entityTypeID, $rootEntityID, $userID));
         }
         if ($enablePermissionCheck && $permissionSql !== '') {
             $query->addFilter('@ENTITY_ID', new Main\DB\SqlExpression($permissionSql));
         }
         $dbResult = $query->exec();
         while ($fields = $dbResult->fetch()) {
             $entityID = isset($fields['ENTITY_ID']) ? intval($fields['ENTITY_ID']) : 0;
             if ($entityID <= 0) {
                 continue;
             }
             $entity = new DuplicateEntity($entityTypeID, $entityID);
             $entity->setCriterion(self::createFromMatches(array('LAST_NAME' => $lastName, 'NAME' => $name)));
             if ($enableRanking) {
                 $rankings[] = $entity->getRanking();
             }
             $dup->addEntity($entity);
         }
     }
     if ($name !== '') {
         $query = new Main\Entity\Query(DuplicatePersonMatchCodeTable::getEntity());
         $query->addSelect('ENTITY_ID');
         $query->addFilter('=ENTITY_TYPE_ID', $entityTypeID);
         $query->addFilter('=LAST_NAME', $lastName);
         $query->addFilter('=NAME', '');
         $query->addFilter('=SECOND_NAME', '');
         if ($rootEntityID) {
             $query->addFilter('!ENTITY_ID', $rootEntityID);
             $query->addFilter('!@ENTITY_ID', DuplicateIndexMismatch::prepareQueryField(self::createFromMatches(array('LAST_NAME' => $lastName)), $entityTypeID, $rootEntityID, $userID));
         }
         if ($enablePermissionCheck && $permissionSql !== '') {
             $query->addFilter('@ENTITY_ID', new Main\DB\SqlExpression($permissionSql));
         }
         $dbResult = $query->exec();
         while ($fields = $dbResult->fetch()) {
             $entityID = isset($fields['ENTITY_ID']) ? intval($fields['ENTITY_ID']) : 0;
             if ($entityID <= 0) {
                 continue;
             }
             $entity = new DuplicateEntity($entityTypeID, $entityID);
             $entity->setCriterion(self::createFromMatches(array('LAST_NAME' => $lastName)));
             if ($enableRanking) {
                 $rankings[] = $entity->getRanking();
             }
             $dup->addEntity($entity);
         }
     }
 }