Exemplo n.º 1
0
 public function getSourceFields()
 {
     if ($this->srcFields !== null) {
         return $this->srcFields;
     }
     $dbResult = \CCrmDeal::GetListEx(array(), array('=ID' => $this->srcEntityID, 'CHECK_PERMISSIONS' => 'N'), false, false, array('*', 'UF_*'));
     $result = $dbResult->Fetch();
     return $this->srcFields = is_array($result) ? $result : array();
 }
Exemplo n.º 2
0
$arResult['PATH_TO_DEAL_SHOW'] = $arParams['PATH_TO_DEAL_SHOW'] = CrmCheckPath('PATH_TO_DEAL_SHOW', $arParams['PATH_TO_DEAL_SHOW'], $APPLICATION->GetCurPage() . '?deal_id=#deal_id#&show');
$arParams['PATH_TO_DEAL_EDIT'] = CrmCheckPath('PATH_TO_DEAL_EDIT', $arParams['PATH_TO_DEAL_EDIT'], $APPLICATION->GetCurPage() . '?deal_id=#deal_id#&edit');
$arParams['PATH_TO_CONTACT_SHOW'] = CrmCheckPath('PATH_TO_CONTACT_SHOW', $arParams['PATH_TO_CONTACT_SHOW'], $APPLICATION->GetCurPage() . '?contact_id=#contact_id#&show');
$arParams['PATH_TO_CONTACT_EDIT'] = CrmCheckPath('PATH_TO_CONTACT_EDIT', $arParams['PATH_TO_CONTACT_EDIT'], $APPLICATION->GetCurPage() . '?contact_id=#contact_id#&edit');
$arParams['PATH_TO_COMPANY_SHOW'] = CrmCheckPath('PATH_TO_COMPANY_SHOW', $arParams['PATH_TO_COMPANY_SHOW'], $APPLICATION->GetCurPage() . '?company_id=#company_id#&show');
$arParams['PATH_TO_COMPANY_EDIT'] = CrmCheckPath('PATH_TO_COMPANY_EDIT', $arParams['PATH_TO_COMPANY_EDIT'], $APPLICATION->GetCurPage() . '?company_id=#company_id#&edit');
$arParams['PATH_TO_LEAD_SHOW'] = CrmCheckPath('PATH_TO_LEAD_SHOW', $arParams['PATH_TO_LEAD_SHOW'], $APPLICATION->GetCurPage() . '?lead_id=#lead_id#&show');
$arParams['PATH_TO_LEAD_EDIT'] = CrmCheckPath('PATH_TO_LEAD_EDIT', $arParams['PATH_TO_LEAD_EDIT'], $APPLICATION->GetCurPage() . '?lead_id=#lead_id#&edit');
$arParams['PATH_TO_LEAD_CONVERT'] = CrmCheckPath('PATH_TO_LEAD_CONVERT', $arParams['PATH_TO_LEAD_CONVERT'], $APPLICATION->GetCurPage() . '?lead_id=#lead_id#&convert');
$arParams['PATH_TO_USER_PROFILE'] = CrmCheckPath('PATH_TO_USER_PROFILE', $arParams['PATH_TO_USER_PROFILE'], '/company/personal/user/#user_id#/');
$arParams['PATH_TO_PRODUCT_EDIT'] = CrmCheckPath('PATH_TO_PRODUCT_EDIT', $arParams['PATH_TO_PRODUCT_EDIT'], $APPLICATION->GetCurPage() . '?product_id=#product_id#&edit');
$arParams['PATH_TO_PRODUCT_SHOW'] = CrmCheckPath('PATH_TO_PRODUCT_SHOW', $arParams['PATH_TO_PRODUCT_SHOW'], $APPLICATION->GetCurPage() . '?product_id=#product_id#&show');
$arParams['NAME_TEMPLATE'] = empty($arParams['NAME_TEMPLATE']) ? CSite::GetNameFormat(false) : str_replace(array("#NOBR#", "#/NOBR#"), array("", ""), $arParams["NAME_TEMPLATE"]);
global $USER_FIELD_MANAGER;
$CCrmUserType = new CCrmUserType($USER_FIELD_MANAGER, CCrmDeal::$sUFEntityID);
$obFields = CCrmDeal::GetListEx(array(), array('ID' => $arParams['ELEMENT_ID']));
$arFields = $obFields->GetNext();
$arFields['CONTACT_FM'] = array();
if (isset($arFields['CONTACT_ID']) && intval($arFields['CONTACT_ID']) > 0) {
    $dbResMultiFields = CCrmFieldMulti::GetList(array('ID' => 'asc'), array('ENTITY_ID' => 'CONTACT', 'ELEMENT_ID' => $arFields['CONTACT_ID']));
    while ($arMultiFields = $dbResMultiFields->Fetch()) {
        $arFields['CONTACT_FM'][$arMultiFields['TYPE_ID']][$arMultiFields['ID']] = array('VALUE' => $arMultiFields['VALUE'], 'VALUE_TYPE' => $arMultiFields['VALUE_TYPE']);
    }
}
$arFields['COMPANY_FM'] = array();
if (isset($arFields['COMPANY_ID']) && intval($arFields['COMPANY_ID']) > 0) {
    $dbResMultiFields = CCrmFieldMulti::GetList(array('ID' => 'asc'), array('ENTITY_ID' => 'COMPANY', 'ELEMENT_ID' => $arFields['COMPANY_ID']));
    while ($arMultiFields = $dbResMultiFields->Fetch()) {
        $arFields['COMPANY_FM'][$arMultiFields['TYPE_ID']][$arMultiFields['ID']] = array('VALUE' => $arMultiFields['VALUE'], 'VALUE_TYPE' => $arMultiFields['VALUE_TYPE']);
    }
}
Exemplo n.º 3
0
    if (!CCrmDeal::CheckUpdatePermission($ID, $curUserPrems)) {
        __CrmMobileDealEditEndResonse(array('ERROR' => GetMessage('CRM_ACCESS_DENIED')));
    }
    $stageID = isset($data['STAGE_ID']) ? $data['STAGE_ID'] : '';
    if ($stageID === '') {
        __CrmMobileDealEditEndResonse(array('ERROR' => GetMessage('CRM_DEAL_STAGE_NOT_FOUND')));
    }
    //$DB->StartTransaction();
    $fields = array('STAGE_ID' => $stageID);
    $entity = new CCrmDeal(false);
    $successed = $entity->Update($ID, $fields, true, true, array());
    if ($successed) {
        //$DB->Commit();
        $errors = array();
        CCrmBizProcHelper::AutoStartWorkflows(CCrmOwnerType::Deal, $ID, CCrmBizProcEventType::Edit, $errors);
        $dbRes = CCrmDeal::GetListEx(array(), array('=ID' => $ID, 'CHECK_PERMISSIONS' => 'N'));
        $currentItem = $dbRes->GetNext();
        $formatParams = isset($_REQUEST['FORMAT_PARAMS']) ? $_REQUEST['FORMAT_PARAMS'] : array();
        CCrmMobileHelper::PrepareDealItem($currentItem, $formatParams);
        __CrmMobileDealEditEndResonse(array('SAVED_ENTITY_ID' => $ID, 'SAVED_ENTITY_DATA' => CCrmMobileHelper::PrepareDealData($currentItem)));
    } else {
        //$DB->Rollback();
        __CrmMobileDealEditEndResonse(array('ERROR' => $fields['RESULT_MESSAGE']));
    }
} elseif ($action === 'CONVERT_MONEY') {
    __IncludeLang(dirname(__FILE__) . '/lang/' . LANGUAGE_ID . '/' . basename(__FILE__));
    $srcCurrencyID = isset($_REQUEST['SRC_CURRENCY_ID']) ? $_REQUEST['SRC_CURRENCY_ID'] : CCrmCurrency::GetBaseCurrencyID();
    $dstCurrencyID = isset($_REQUEST['DST_CURRENCY_ID']) ? $_REQUEST['DST_CURRENCY_ID'] : CCrmCurrency::GetBaseCurrencyID();
    $srcSum = isset($_REQUEST['SUM']) ? doubleval($_REQUEST['SUM']) : 0.0;
    $dstSum = CCrmCurrency::ConvertMoney($srcSum, $srcCurrencyID, $dstCurrencyID);
    __CrmMobileDealEditEndResonse(array('SUM' => $dstSum, 'CURRENCY_ID' => $dstCurrencyID, 'CURRENCY_NAME' => CCrmCurrency::GetCurrencyName($dstCurrencyID), 'FORMATTED_SUM' => CCrmCurrency::MoneyToString($dstSum, $dstCurrencyID)));
Exemplo n.º 4
0
     }
     unset($dbContact, $arContact);
 }
 // create from company
 if ($companyId > 0) {
     $dbCompany = CCrmCompany::GetListEx(array('ID' => 'DESC'), array('ID' => $companyId), false, array('nTopCount' => 1), array('ID', 'LEAD_ID'));
     if ($arCompany = $dbCompany->Fetch()) {
         if (isset($arCompany['LEAD_ID']) && intval($arCompany['LEAD_ID']) > 0) {
             $arFields['~LEAD_ID'] = $arFields['LEAD_ID'] = intval($arCompany['LEAD_ID']);
         }
     }
     unset($dbCompany, $arCompany);
 }
 // create from lead
 if ($leadId > 0) {
     $dbDeal = CCrmDeal::GetListEx(array('ID' => 'DESC'), array('LEAD_ID' => $leadId), false, array('nTopCount' => 1), array('ID'));
     if ($arDeal = $dbDeal->Fetch()) {
         if (isset($arDeal['ID']) && intval($arDeal['ID']) > 0) {
             $arFields['~DEAL_ID'] = $arFields['DEAL_ID'] = intval($arDeal['ID']);
         }
     }
     unset($dbDeal, $arDeal);
     if (($arLead = CCrmLead::GetByID($leadId)) && is_array($arLead)) {
         // get contact and/or company from lead
         if ($companyId <= 0 || $contactId <= 0) {
             if (isset($arLead['CONTACT_ID']) && intval($arLead['CONTACT_ID']) > 0) {
                 $arFields['~CONTACT_ID'] = $arFields['CONTACT_ID'] = intval($arLead['CONTACT_ID']);
             }
             if (isset($arLead['COMPANY_ID']) && intval($arLead['COMPANY_ID']) > 0) {
                 $arFields['~COMPANY_ID'] = $arFields['COMPANY_ID'] = intval($arLead['COMPANY_ID']);
             }
 public static function PreparePopupItems($entityTypeNames, $addPrefix = true, $nameFormat = '', $count = 50)
 {
     if (!is_array($entityTypeNames)) {
         $entityTypeNames = array(strval($entityTypeNames));
     }
     $addPrefix = (bool) $addPrefix;
     $count = intval($count);
     if ($count <= 0) {
         $count = 50;
     }
     $arItems = array();
     $i = 0;
     foreach ($entityTypeNames as $typeName) {
         $typeName = strtoupper(strval($typeName));
         if ($typeName === 'CONTACT') {
             $contactTypes = CCrmStatus::GetStatusList('CONTACT_TYPE');
             $contactIndex = array();
             $obRes = CCrmContact::GetListEx(array('ID' => 'DESC'), array(), false, array('nTopCount' => $count), array('ID', 'HONORIFIC', 'NAME', 'SECOND_NAME', 'LAST_NAME', 'COMPANY_TITLE', 'PHOTO', 'TYPE_ID'));
             while ($arRes = $obRes->Fetch()) {
                 $arImg = array();
                 if (!empty($arRes['PHOTO']) && !isset($arFiles[$arRes['PHOTO']])) {
                     if (intval($arRes['PHOTO']) > 0) {
                         $arImg = CFile::ResizeImageGet($arRes['PHOTO'], array('width' => 25, 'height' => 25), BX_RESIZE_IMAGE_EXACT);
                     }
                 }
                 $arRes['SID'] = $addPrefix ? 'C_' . $arRes['ID'] : $arRes['ID'];
                 // advanced info
                 $advancedInfo = array();
                 if (isset($arRes['TYPE_ID']) && $arRes['TYPE_ID'] != '' && isset($contactTypes[$arRes['TYPE_ID']])) {
                     $advancedInfo['contactType'] = array('id' => $arRes['TYPE_ID'], 'name' => $contactTypes[$arRes['TYPE_ID']]);
                 }
                 $arItems[$i] = array('title' => CCrmContact::PrepareFormattedName(array('HONORIFIC' => isset($arRes['HONORIFIC']) ? $arRes['HONORIFIC'] : '', 'NAME' => isset($arRes['NAME']) ? $arRes['NAME'] : '', 'SECOND_NAME' => isset($arRes['SECOND_NAME']) ? $arRes['SECOND_NAME'] : '', 'LAST_NAME' => isset($arRes['LAST_NAME']) ? $arRes['LAST_NAME'] : ''), $nameFormat), 'desc' => empty($arRes['COMPANY_TITLE']) ? "" : $arRes['COMPANY_TITLE'], 'id' => $arRes['SID'], 'url' => CComponentEngine::MakePathFromTemplate(COption::GetOptionString('crm', 'path_to_contact_show'), array('contact_id' => $arRes['ID'])), 'image' => $arImg['src'], 'type' => 'contact', 'selected' => 'N');
                 if (!empty($advancedInfo)) {
                     $arItems[$i]['advancedInfo'] = $advancedInfo;
                 }
                 unset($advancedInfo);
                 $contactIndex[$arRes['ID']] =& $arItems[$i];
                 $i++;
             }
             // advanced info - phone number, e-mail
             $obRes = CCrmFieldMulti::GetList(array('ID' => 'asc'), array('ENTITY_ID' => 'CONTACT', 'ELEMENT_ID' => array_keys($contactIndex)));
             while ($arRes = $obRes->Fetch()) {
                 if (isset($contactIndex[$arRes['ELEMENT_ID']]) && ($arRes['TYPE_ID'] === 'PHONE' || $arRes['TYPE_ID'] === 'EMAIL')) {
                     $item =& $contactIndex[$arRes['ELEMENT_ID']];
                     if (!is_array($item['advancedInfo'])) {
                         $item['advancedInfo'] = array();
                     }
                     if (!is_array($item['advancedInfo']['multiFields'])) {
                         $item['advancedInfo']['multiFields'] = array();
                     }
                     $item['advancedInfo']['multiFields'][] = array('ID' => $arRes['ID'], 'TYPE_ID' => $arRes['TYPE_ID'], 'VALUE_TYPE' => $arRes['VALUE_TYPE'], 'VALUE' => $arRes['VALUE']);
                     unset($item);
                 }
             }
             unset($contactIndex);
         } elseif ($typeName === 'COMPANY') {
             $companyIndex = array();
             $arCompanyTypeList = CCrmStatus::GetStatusListEx('COMPANY_TYPE');
             $arCompanyIndustryList = CCrmStatus::GetStatusListEx('INDUSTRY');
             $obRes = CCrmCompany::GetListEx(array('ID' => 'DESC'), array(), false, array('nTopCount' => $count), array('ID', 'TITLE', 'COMPANY_TYPE', 'INDUSTRY', 'LOGO'));
             $arFiles = array();
             while ($arRes = $obRes->Fetch()) {
                 $arImg = array();
                 if (!empty($arRes['LOGO']) && !isset($arFiles[$arRes['LOGO']])) {
                     if (intval($arRes['LOGO']) > 0) {
                         $arImg = CFile::ResizeImageGet($arRes['LOGO'], array('width' => 25, 'height' => 25), BX_RESIZE_IMAGE_EXACT);
                     }
                     $arFiles[$arRes['LOGO']] = $arImg['src'];
                 }
                 $arRes['SID'] = $addPrefix ? 'CO_' . $arRes['ID'] : $arRes['ID'];
                 $arDesc = array();
                 if (isset($arCompanyTypeList[$arRes['COMPANY_TYPE']])) {
                     $arDesc[] = $arCompanyTypeList[$arRes['COMPANY_TYPE']];
                 }
                 if (isset($arCompanyIndustryList[$arRes['INDUSTRY']])) {
                     $arDesc[] = $arCompanyIndustryList[$arRes['INDUSTRY']];
                 }
                 $arItems[$i] = array('title' => str_replace(array(';', ','), ' ', $arRes['TITLE']), 'desc' => implode(', ', $arDesc), 'id' => $arRes['SID'], 'url' => CComponentEngine::MakePathFromTemplate(COption::GetOptionString('crm', 'path_to_company_show'), array('company_id' => $arRes['ID'])), 'image' => $arImg['src'], 'type' => 'company', 'selected' => 'N');
                 $companyIndex[$arRes['ID']] =& $arItems[$i];
                 $i++;
             }
             // advanced info - phone number, e-mail
             $obRes = CCrmFieldMulti::GetList(array('ID' => 'asc'), array('ENTITY_ID' => 'COMPANY', 'ELEMENT_ID' => array_keys($companyIndex)));
             while ($arRes = $obRes->Fetch()) {
                 if (isset($companyIndex[$arRes['ELEMENT_ID']]) && ($arRes['TYPE_ID'] === 'PHONE' || $arRes['TYPE_ID'] === 'EMAIL')) {
                     $item =& $companyIndex[$arRes['ELEMENT_ID']];
                     if (!is_array($item['advancedInfo'])) {
                         $item['advancedInfo'] = array();
                     }
                     if (!is_array($item['advancedInfo']['multiFields'])) {
                         $item['advancedInfo']['multiFields'] = array();
                     }
                     $item['advancedInfo']['multiFields'][] = array('ID' => $arRes['ID'], 'TYPE_ID' => $arRes['TYPE_ID'], 'VALUE_TYPE' => $arRes['VALUE_TYPE'], 'VALUE' => $arRes['VALUE']);
                     unset($item);
                 }
             }
             unset($companyIndex);
         } elseif ($typeName === 'LEAD') {
             $leadIndex = array();
             $obRes = CCrmLead::GetListEx(array('ID' => 'DESC'), array(), false, array('nTopCount' => $count), array('ID', 'TITLE', 'NAME', 'SECOND_NAME', 'LAST_NAME', 'STATUS_ID'));
             while ($arRes = $obRes->Fetch()) {
                 $arRes['SID'] = $addPrefix ? 'L_' . $arRes['ID'] : $arRes['ID'];
                 $arItems[$i] = array('title' => isset($arRes['TITLE']) ? $arRes['TITLE'] : '', 'desc' => CCrmLead::PrepareFormattedName(array('HONORIFIC' => isset($arRes['HONORIFIC']) ? $arRes['HONORIFIC'] : '', 'NAME' => isset($arRes['NAME']) ? $arRes['NAME'] : '', 'SECOND_NAME' => isset($arRes['SECOND_NAME']) ? $arRes['SECOND_NAME'] : '', 'LAST_NAME' => isset($arRes['LAST_NAME']) ? $arRes['LAST_NAME'] : ''), $nameFormat), 'id' => $arRes['SID'], 'url' => CComponentEngine::MakePathFromTemplate(COption::GetOptionString('crm', 'path_to_lead_show'), array('lead_id' => $arRes['ID'])), 'type' => 'lead', 'selected' => 'N');
                 $leadIndex[$arRes['ID']] =& $arItems[$i];
                 $i++;
             }
             // advanced info - phone number, e-mail
             $obRes = CCrmFieldMulti::GetList(array('ID' => 'asc'), array('ENTITY_ID' => 'LEAD', 'ELEMENT_ID' => array_keys($leadIndex)));
             while ($arRes = $obRes->Fetch()) {
                 if (isset($leadIndex[$arRes['ELEMENT_ID']]) && ($arRes['TYPE_ID'] === 'PHONE' || $arRes['TYPE_ID'] === 'EMAIL')) {
                     $item =& $leadIndex[$arRes['ELEMENT_ID']];
                     if (!is_array($item['advancedInfo'])) {
                         $item['advancedInfo'] = array();
                     }
                     if (!is_array($item['advancedInfo']['multiFields'])) {
                         $item['advancedInfo']['multiFields'] = array();
                     }
                     $item['advancedInfo']['multiFields'][] = array('ID' => $arRes['ID'], 'TYPE_ID' => $arRes['TYPE_ID'], 'VALUE_TYPE' => $arRes['VALUE_TYPE'], 'VALUE' => $arRes['VALUE']);
                     unset($item);
                 }
             }
             unset($leadIndex);
         } elseif ($typeName === 'DEAL') {
             $obRes = CCrmDeal::GetListEx(array('ID' => 'DESC'), array(), false, array('nTopCount' => $count), array('ID', 'TITLE', 'STAGE_ID', 'COMPANY_TITLE', 'CONTACT_FULL_NAME'));
             while ($arRes = $obRes->Fetch()) {
                 $arRes['SID'] = $addPrefix ? 'D_' . $arRes['ID'] : $arRes['ID'];
                 $clientTitle = !empty($arRes['COMPANY_TITLE']) ? $arRes['COMPANY_TITLE'] : '';
                 $clientTitle .= ($clientTitle !== '' && !empty($arRes['CONTACT_FULL_NAME']) ? ', ' : '') . $arRes['CONTACT_FULL_NAME'];
                 $arItems[] = array('title' => isset($arRes['TITLE']) ? str_replace(array(';', ','), ' ', $arRes['TITLE']) : '', 'desc' => $clientTitle, 'id' => $arRes['SID'], 'url' => CComponentEngine::MakePathFromTemplate(COption::GetOptionString('crm', 'path_to_deal_show'), array('deal_id' => $arRes['ID'])), 'type' => 'deal', 'selected' => 'N');
             }
         } elseif ($typeName === 'QUOTE') {
             $obRes = CCrmQuote::GetList(array('ID' => 'DESC'), array(), false, array('nTopCount' => $count), array('ID', 'QUOTE_NUMBER', 'TITLE', 'COMPANY_TITLE', 'CONTACT_FULL_NAME'));
             while ($arRes = $obRes->Fetch()) {
                 $arRes['SID'] = $addPrefix ? CCrmQuote::OWNER_TYPE . '_' . $arRes['ID'] : $arRes['ID'];
                 $clientTitle = !empty($arRes['COMPANY_TITLE']) ? $arRes['COMPANY_TITLE'] : '';
                 $clientTitle .= ($clientTitle !== '' && !empty($arRes['CONTACT_FULL_NAME']) ? ', ' : '') . $arRes['CONTACT_FULL_NAME'];
                 $quoteTitle = empty($arRes['TITLE']) ? $arRes['QUOTE_NUMBER'] : $arRes['QUOTE_NUMBER'] . ' - ' . $arRes['TITLE'];
                 $arItems[] = array('title' => empty($quoteTitle) ? '' : str_replace(array(';', ','), ' ', $quoteTitle), 'desc' => $clientTitle, 'id' => $arRes['SID'], 'url' => CComponentEngine::MakePathFromTemplate(COption::GetOptionString('crm', 'path_to_quote_show'), array('quote_id' => $arRes['ID'])), 'type' => 'quote', 'selected' => 'N');
             }
         }
     }
     unset($typeName);
     return $arItems;
 }
Exemplo n.º 6
0
                $fieldName = $arMatch[1];
                if (($fieldName == 'DATE_CREATE' || $fieldName == 'DATE_MODIFY' || $fieldName == 'BEGINDATE' || $fieldName == 'CLOSEDATE') && !preg_match('/\\d{1,2}:\\d{1,2}(:\\d{1,2})?$/' . BX_UTF_PCRE_MODIFIER, $v)) {
                    $v .= ' 23:59:59';
                }
                $arFilter['<=' . $arMatch[1]] = $v;
            }
            unset($arFilter[$k]);
        } else {
            if (strpos($k, 'UF_') !== 0 && $k != 'LOGIC') {
                $arFilter['%' . $k] = $v;
                unset($arFilter[$k]);
            }
        }
    }
}
$obRes = CCrmDeal::GetListEx(array(), $arFilter, false, false, array('ID', 'TITLE', 'STAGE_ID', 'OPPORTUNITY', 'CURRENCY_ID'));
$arResult['DEAL'] = array();
$arResult['STAGE_COUNT'] = array();
$arResult['FUNNEL'] = array();
$iDealCount = 0;
while ($arDeal = $obRes->GetNext()) {
    //Normalizing for compatibility
    $currencyID = CCrmCurrency::NormalizeCurrencyID($arDeal['CURRENCY_ID']);
    $stageID = $arDeal['STAGE_ID'];
    $opportunity = (double) $arDeal['OPPORTUNITY'];
    if (!isset($arResult['STAGE_COUNT'][$stageID])) {
        $arResult['STAGE_COUNT'][$stageID]['COUNT'] = 1;
        $arResult['STAGE_COUNT'][$stageID]['COUNT_FUNNEL'] = 1;
        $arResult['STAGE_COUNT'][$stageID]['OPPORTUNITY'] = array($currencyID => $opportunity);
        $arResult['STAGE_COUNT'][$stageID]['OPPORTUNITY_FUNNEL'] = array($currencyID => $opportunity);
    } else {
Exemplo n.º 7
0
 public function Update($ID, array &$arFields, $bCompare = true, $bUpdateSearch = true, $options = array())
 {
     global $DB;
     $this->LAST_ERROR = '';
     $ID = (int) $ID;
     if (!is_array($options)) {
         $options = array();
     }
     $arFilterTmp = array('ID' => $ID);
     if (!$this->bCheckPermission) {
         $arFilterTmp['CHECK_PERMISSIONS'] = 'N';
     }
     $obRes = self::GetListEx(array(), $arFilterTmp);
     if (!($arRow = $obRes->Fetch())) {
         return false;
     }
     $iUserId = CCrmSecurityHelper::GetCurrentUserID();
     if (isset($arFields['DATE_CREATE'])) {
         unset($arFields['DATE_CREATE']);
     }
     if (isset($arFields['DATE_MODIFY'])) {
         unset($arFields['DATE_MODIFY']);
     }
     $arFields['~DATE_MODIFY'] = $DB->CurrentTimeFunction();
     if (!isset($arFields['MODIFY_BY_ID']) || $arFields['MODIFY_BY_ID'] <= 0) {
         $arFields['MODIFY_BY_ID'] = $iUserId;
     }
     if (isset($arFields['ASSIGNED_BY_ID']) && $arFields['ASSIGNED_BY_ID'] <= 0) {
         unset($arFields['ASSIGNED_BY_ID']);
     }
     $assignedByID = (int) (isset($arFields['ASSIGNED_BY_ID']) ? $arFields['ASSIGNED_BY_ID'] : $arRow['ASSIGNED_BY_ID']);
     $bResult = false;
     if (!$this->CheckFields($arFields, $ID, $options)) {
         $arFields['RESULT_MESSAGE'] =& $this->LAST_ERROR;
     } else {
         if ($this->bCheckPermission && !CCrmAuthorizationHelper::CheckUpdatePermission(self::$TYPE_NAME, $ID, $this->cPerms)) {
             $this->LAST_ERROR = GetMessage('CRM_PERMISSION_DENIED');
             $arFields['RESULT_MESSAGE'] =& $this->LAST_ERROR;
             return false;
         }
         $beforeEvents = GetModuleEvents('crm', 'OnBeforeCrmDealUpdate');
         while ($arEvent = $beforeEvents->Fetch()) {
             if (ExecuteModuleEventEx($arEvent, array(&$arFields)) === false) {
                 if (isset($arFields['RESULT_MESSAGE'])) {
                     $this->LAST_ERROR = $arFields['RESULT_MESSAGE'];
                 } else {
                     $this->LAST_ERROR = GetMessage('CRM_DEAL_UPDATE_CANCELED', array('#NAME#' => $arEvent['TO_NAME']));
                     $arFields['RESULT_MESSAGE'] =& $this->LAST_ERROR;
                 }
                 return false;
             }
         }
         $arAttr = array();
         $arAttr['STAGE_ID'] = !empty($arFields['STAGE_ID']) ? $arFields['STAGE_ID'] : $arRow['STAGE_ID'];
         $arAttr['OPENED'] = !empty($arFields['OPENED']) ? $arFields['OPENED'] : $arRow['OPENED'];
         $arEntityAttr = self::BuildEntityAttr($assignedByID, $arAttr);
         $sEntityPerm = $this->cPerms->GetPermType('DEAL', 'WRITE', $arEntityAttr);
         $this->PrepareEntityAttrs($arEntityAttr, $sEntityPerm);
         //Prevent 'OPENED' field change by user restricted by BX_CRM_PERM_OPEN permission
         if ($sEntityPerm === BX_CRM_PERM_OPEN && isset($arFields['OPENED']) && $arFields['OPENED'] !== 'Y' && $assignedByID !== $iUserId) {
             $arFields['OPENED'] = 'Y';
         }
         if (isset($arFields['ASSIGNED_BY_ID']) && $arRow['ASSIGNED_BY_ID'] != $arFields['ASSIGNED_BY_ID']) {
             CCrmEvent::SetAssignedByElement($arFields['ASSIGNED_BY_ID'], 'DEAL', $ID);
         }
         $sonetEventData = array();
         if ($bCompare) {
             $arEvents = self::CompareFields($arRow, $arFields, $this->bCheckPermission);
             foreach ($arEvents as $arEvent) {
                 $arEvent['ENTITY_TYPE'] = 'DEAL';
                 $arEvent['ENTITY_ID'] = $ID;
                 $arEvent['EVENT_TYPE'] = 1;
                 if (!isset($arEvent['USER_ID'])) {
                     $arEvent['USER_ID'] = $iUserId;
                 }
                 $CCrmEvent = new CCrmEvent();
                 $eventID = $CCrmEvent->Add($arEvent, $this->bCheckPermission);
                 if (is_int($eventID) && $eventID > 0) {
                     $fieldID = isset($arEvent['ENTITY_FIELD']) ? $arEvent['ENTITY_FIELD'] : '';
                     if ($fieldID === '') {
                         continue;
                     }
                     switch ($fieldID) {
                         case 'STAGE_ID':
                             $sonetEventData[CCrmLiveFeedEvent::Progress] = array('TYPE' => CCrmLiveFeedEvent::Progress, 'FIELDS' => array('TITLE' => GetMessage('CRM_DEAL_EVENT_UPDATE_STAGE'), 'MESSAGE' => '', 'PARAMS' => array('START_STATUS_ID' => $arRow['STAGE_ID'], 'FINAL_STATUS_ID' => $arFields['STAGE_ID'])));
                             break;
                         case 'ASSIGNED_BY_ID':
                             $sonetEventData[CCrmLiveFeedEvent::Responsible] = array('TYPE' => CCrmLiveFeedEvent::Responsible, 'FIELDS' => array('TITLE' => GetMessage('CRM_DEAL_EVENT_UPDATE_ASSIGNED_BY'), 'MESSAGE' => '', 'PARAMS' => array('START_RESPONSIBLE_ID' => $arRow['ASSIGNED_BY_ID'], 'FINAL_RESPONSIBLE_ID' => $arFields['ASSIGNED_BY_ID'])));
                             break;
                         case 'CONTACT_ID':
                         case 'COMPANY_ID':
                             if (!isset($sonetEventData[CCrmLiveFeedEvent::Client])) {
                                 $oldContactID = isset($arRow['CONTACT_ID']) ? intval($arRow['CONTACT_ID']) : 0;
                                 $oldCompanyID = isset($arRow['COMPANY_ID']) ? intval($arRow['COMPANY_ID']) : 0;
                                 $sonetEventData[CCrmLiveFeedEvent::Client] = array('CODE' => 'CLIENT', 'TYPE' => CCrmLiveFeedEvent::Client, 'FIELDS' => array('TITLE' => GetMessage('CRM_DEAL_EVENT_UPDATE_CLIENT'), 'MESSAGE' => '', 'PARAMS' => array('START_CLIENT_CONTACT_ID' => $oldContactID, 'FINAL_CLIENT_CONTACT_ID' => isset($arFields['CONTACT_ID']) ? intval($arFields['CONTACT_ID']) : $oldContactID, 'START_CLIENT_COMPANY_ID' => $oldCompanyID, 'FINAL_CLIENT_COMPANY_ID' => isset($arFields['COMPANY_ID']) ? intval($arFields['COMPANY_ID']) : $oldCompanyID)));
                             }
                             break;
                         case 'TITLE':
                             $sonetEventData[CCrmLiveFeedEvent::Denomination] = array('TYPE' => CCrmLiveFeedEvent::Denomination, 'FIELDS' => array('TITLE' => GetMessage('CRM_DEAL_EVENT_UPDATE_TITLE'), 'MESSAGE' => '', 'PARAMS' => array('START_TITLE' => $arRow['TITLE'], 'FINAL_TITLE' => $arFields['TITLE'])));
                             break;
                     }
                 }
             }
             // CHECK IF COMPANY/CONTACT WAS ADDED/REMOVED
             if (!isset($sonetEventData[CCrmLiveFeedEvent::Client]) && (!isset($arRow['COMPANY_ID']) && isset($arFields['COMPANY_ID']) || isset($arRow['COMPANY_ID']) && !isset($arFields['COMPANY_ID']) || !isset($arRow['CONTACT_ID']) && isset($arFields['CONTACT_ID']) || isset($arRow['CONTACT_ID']) && !isset($arFields['CONTACT_ID']))) {
                 $sonetEventData[CCrmLiveFeedEvent::Client] = array('CODE' => 'CLIENT', 'TYPE' => CCrmLiveFeedEvent::Client, 'FIELDS' => array('TITLE' => GetMessage('CRM_DEAL_EVENT_UPDATE_CLIENT'), 'MESSAGE' => '', 'PARAMS' => array('START_CLIENT_CONTACT_ID' => isset($arRow['CONTACT_ID']) ? intval($arRow['CONTACT_ID']) : 0, 'FINAL_CLIENT_CONTACT_ID' => isset($arFields['CONTACT_ID']) ? intval($arFields['CONTACT_ID']) : 0, 'START_CLIENT_COMPANY_ID' => isset($arRow['COMPANY_ID']) ? intval($arRow['COMPANY_ID']) : 0, 'FINAL_CLIENT_COMPANY_ID' => isset($arFields['COMPANY_ID']) ? intval($arFields['COMPANY_ID']) : 0)));
             }
         }
         // Calculation of Account Data
         $accData = CCrmAccountingHelper::PrepareAccountingData(array('CURRENCY_ID' => isset($arFields['CURRENCY_ID']) ? $arFields['CURRENCY_ID'] : (isset($arRow['CURRENCY_ID']) ? $arRow['CURRENCY_ID'] : null), 'SUM' => isset($arFields['OPPORTUNITY']) ? $arFields['OPPORTUNITY'] : (isset($arRow['OPPORTUNITY']) ? $arRow['OPPORTUNITY'] : null), 'EXCH_RATE' => isset($arFields['EXCH_RATE']) ? $arFields['EXCH_RATE'] : (isset($arRow['EXCH_RATE']) ? $arRow['EXCH_RATE'] : null)));
         if (is_array($accData)) {
             $arFields['ACCOUNT_CURRENCY_ID'] = $accData['ACCOUNT_CURRENCY_ID'];
             $arFields['OPPORTUNITY_ACCOUNT'] = $accData['ACCOUNT_SUM'];
         }
         $accData = CCrmAccountingHelper::PrepareAccountingData(array('CURRENCY_ID' => isset($arFields['CURRENCY_ID']) ? $arFields['CURRENCY_ID'] : (isset($arRow['CURRENCY_ID']) ? $arRow['CURRENCY_ID'] : null), 'SUM' => isset($arFields['TAX_VALUE']) ? $arFields['TAX_VALUE'] : (isset($arRow['TAX_VALUE']) ? $arRow['TAX_VALUE'] : null), 'EXCH_RATE' => isset($arFields['EXCH_RATE']) ? $arFields['EXCH_RATE'] : (isset($arRow['EXCH_RATE']) ? $arRow['EXCH_RATE'] : null)));
         if (is_array($accData)) {
             $arFields['TAX_VALUE_ACCOUNT'] = $accData['ACCOUNT_SUM'];
         }
         $enableCloseDateSync = \Bitrix\Crm\Settings\DealSettings::isCloseDateSyncEnabled();
         if (isset($arFields['STAGE_ID'])) {
             $now = ConvertTimeStamp(time(), 'SHORT', SITE_ID);
             $isFinalStage = self::GetStageSemantics($arFields['STAGE_ID']) !== 'process';
             $isStageChanged = !isset($arRow['STAGE_ID']) || $arRow['STAGE_ID'] !== $arFields['STAGE_ID'];
             $arFields['CLOSED'] = $isFinalStage ? 'Y' : 'N';
             if ($enableCloseDateSync && $isFinalStage && $isStageChanged) {
                 $arFields['CLOSEDATE'] = $now;
                 $arFields['~CLOSEDATE'] = $DB->CharToDateFunction($now, 'SHORT', false);
             } elseif (isset($arFields['CLOSEDATE']) && $arFields['CLOSEDATE'] !== '') {
                 $arFields['~CLOSEDATE'] = $DB->CharToDateFunction($arFields['CLOSEDATE'], 'SHORT', false);
             }
         } elseif ($enableCloseDateSync && self::GetStageSemantics($arRow['STAGE_ID']) !== 'process' && isset($arFields['CLOSEDATE'])) {
             unset($arFields['CLOSEDATE']);
         }
         if (isset($arFields['BEGINDATE']) && $arFields['BEGINDATE'] !== '') {
             $arFields['~BEGINDATE'] = $DB->CharToDateFunction($arFields['BEGINDATE'], 'SHORT', false);
         }
         if (isset($arFields['BEGINDATE'])) {
             $arFields['__BEGINDATE'] = $arFields['BEGINDATE'];
             unset($arFields['BEGINDATE']);
         }
         if (isset($arFields['CLOSEDATE'])) {
             $arFields['__CLOSEDATE'] = $arFields['CLOSEDATE'];
             unset($arFields['CLOSEDATE']);
         }
         unset($arFields['ID']);
         $sUpdate = $DB->PrepareUpdate('b_crm_deal', $arFields);
         if (strlen($sUpdate) > 0) {
             $DB->Query("UPDATE b_crm_deal SET {$sUpdate} WHERE ID = {$ID}", false, 'FILE: ' . __FILE__ . '<br /> LINE: ' . __LINE__);
             $bResult = true;
         }
         //Restore BEGINDATE and CLOSEDATE
         if (isset($arFields['__BEGINDATE'])) {
             $arFields['BEGINDATE'] = $arFields['__BEGINDATE'];
             unset($arFields['__BEGINDATE']);
         }
         if (isset($arFields['__CLOSEDATE'])) {
             $arFields['CLOSEDATE'] = $arFields['__CLOSEDATE'];
             unset($arFields['__CLOSEDATE']);
         }
         if (defined("BX_COMP_MANAGED_CACHE")) {
             static $arNameFields = array("TITLE");
             $bClear = false;
             foreach ($arNameFields as $val) {
                 if (isset($arFields[$val])) {
                     $bClear = true;
                     break;
                 }
             }
             if ($bClear) {
                 $GLOBALS["CACHE_MANAGER"]->ClearByTag("crm_entity_name_" . CCrmOwnerType::Deal . "_" . $ID);
             }
         }
         CCrmPerms::UpdateEntityAttr('DEAL', $ID, $arEntityAttr);
         CCrmEntityHelper::NormalizeUserFields($arFields, self::$sUFEntityID, $GLOBALS['USER_FIELD_MANAGER'], array('IS_NEW' => false));
         $GLOBALS['USER_FIELD_MANAGER']->Update(self::$sUFEntityID, $ID, $arFields);
         //Statistics & History -->
         $currentDbResult = \CCrmDeal::GetListEx(array(), array('=ID' => $ID, 'CHECK_PERMISSIONS' => 'N'), false, false, array('*', 'UF_*'));
         $currentFields = $currentDbResult->Fetch();
         Bitrix\Crm\Statistics\DealSumStatisticEntry::register($ID, $currentFields);
         Bitrix\Crm\History\DealStageHistoryEntry::synchronize($ID, $currentFields);
         Bitrix\Crm\Statistics\DealInvoiceStatisticEntry::synchronize($ID, $currentFields);
         Bitrix\Crm\Statistics\DealActivityStatisticEntry::synchronize($ID, $currentFields);
         if (isset($arFields['STAGE_ID'])) {
             Bitrix\Crm\History\DealStageHistoryEntry::register($ID, $arFields, array('IS_NEW' => false));
         }
         //<-- Statistics & History
         if ($bUpdateSearch) {
             $arFilterTmp = array('ID' => $ID);
             if (!$this->bCheckPermission) {
                 $arFilterTmp['CHECK_PERMISSIONS'] = 'N';
             }
             CCrmSearch::UpdateSearch($arFilterTmp, 'DEAL', true);
         }
         $arFields['ID'] = $ID;
         if (isset($arFields['FM']) && is_array($arFields['FM'])) {
             $CCrmFieldMulti = new CCrmFieldMulti();
             $CCrmFieldMulti->SetFields('DEAL', $ID, $arFields['FM']);
         }
         // Responsible user sync
         //CCrmActivity::Synchronize(CCrmOwnerType::Deal, $ID);
         $registerSonetEvent = isset($options['REGISTER_SONET_EVENT']) && $options['REGISTER_SONET_EVENT'] === true;
         if ($bResult && isset($arFields['ASSIGNED_BY_ID'])) {
             CCrmSonetSubscription::ReplaceSubscriptionByEntity(CCrmOwnerType::Deal, $ID, CCrmSonetSubscriptionType::Responsibility, $arFields['ASSIGNED_BY_ID'], $arRow['ASSIGNED_BY_ID'], $registerSonetEvent);
         }
         if ($bResult && $bCompare && $registerSonetEvent && !empty($sonetEventData)) {
             //CONTACT
             $newContactID = isset($arFields['CONTACT_ID']) ? intval($arFields['CONTACT_ID']) : 0;
             $oldContactID = isset($arRow['CONTACT_ID']) ? intval($arRow['CONTACT_ID']) : 0;
             $contactID = $newContactID > 0 ? $newContactID : $oldContactID;
             //COMPANY
             $newCompanyID = isset($arFields['COMPANY_ID']) ? intval($arFields['COMPANY_ID']) : 0;
             $oldCompanyID = isset($arRow['COMPANY_ID']) ? intval($arRow['COMPANY_ID']) : 0;
             $companyID = $newCompanyID > 0 ? $newCompanyID : $oldCompanyID;
             $modifiedByID = intval($arFields['MODIFY_BY_ID']);
             foreach ($sonetEventData as &$sonetEvent) {
                 $sonetEventType = $sonetEvent['TYPE'];
                 $sonetEventCode = isset($sonetEvent['CODE']) ? $sonetEvent['CODE'] : '';
                 $sonetEventFields =& $sonetEvent['FIELDS'];
                 $sonetEventFields['ENTITY_TYPE_ID'] = CCrmOwnerType::Deal;
                 $sonetEventFields['ENTITY_ID'] = $ID;
                 $sonetEventFields['USER_ID'] = $modifiedByID;
                 //Register contact & company relations
                 if ($sonetEventCode === 'CLIENT') {
                     $sonetEventFields['PARENTS'] = array();
                     //If contact changed bind events to old and new contacts
                     if ($oldContactID !== $newContactID) {
                         if ($oldContactID > 0) {
                             $sonetEventFields['PARENTS'][] = array('ENTITY_TYPE_ID' => CCrmOwnerType::Contact, 'ENTITY_ID' => $oldContactID);
                         }
                         if ($newContactID > 0) {
                             $sonetEventFields['PARENTS'][] = array('ENTITY_TYPE_ID' => CCrmOwnerType::Contact, 'ENTITY_ID' => $newContactID);
                         }
                     }
                     //If company changed bind events to old and new companies
                     if ($oldCompanyID !== $newCompanyID) {
                         if ($oldCompanyID > 0) {
                             $sonetEventFields['PARENTS'][] = array('ENTITY_TYPE_ID' => CCrmOwnerType::Company, 'ENTITY_ID' => $oldCompanyID);
                         }
                         if ($newCompanyID > 0) {
                             $sonetEventFields['PARENTS'][] = array('ENTITY_TYPE_ID' => CCrmOwnerType::Company, 'ENTITY_ID' => $newCompanyID);
                         }
                     }
                 } elseif ($contactID > 0 || $companyID > 0) {
                     $sonetEventFields['PARENTS'] = array();
                     if ($contactID > 0) {
                         $sonetEventFields['PARENTS'][] = array('ENTITY_TYPE_ID' => CCrmOwnerType::Contact, 'ENTITY_ID' => $contactID);
                     }
                     if ($companyID > 0) {
                         $sonetEventFields['PARENTS'][] = array('ENTITY_TYPE_ID' => CCrmOwnerType::Company, 'ENTITY_ID' => $companyID);
                     }
                 }
                 $logEventID = CCrmLiveFeed::CreateLogEvent($sonetEventFields, $sonetEventType);
                 if ($logEventID && CModule::IncludeModule("im")) {
                     $url = CCrmOwnerType::GetShowUrl(CCrmOwnerType::Deal, $ID);
                     $serverName = (CMain::IsHTTPS() ? "https" : "http") . "://" . (defined("SITE_SERVER_NAME") && strlen(SITE_SERVER_NAME) > 0 ? SITE_SERVER_NAME : COption::GetOptionString("main", "server_name", ""));
                     if ($sonetEvent['TYPE'] == CCrmLiveFeedEvent::Responsible && $sonetEventFields['PARAMS']['FINAL_RESPONSIBLE_ID'] != $modifiedByID) {
                         $arMessageFields = array("MESSAGE_TYPE" => IM_MESSAGE_SYSTEM, "TO_USER_ID" => $sonetEventFields['PARAMS']['FINAL_RESPONSIBLE_ID'], "FROM_USER_ID" => $modifiedByID, "NOTIFY_TYPE" => IM_NOTIFY_FROM, "NOTIFY_MODULE" => "crm", "LOG_ID" => $logEventID, "NOTIFY_EVENT" => "deal_update", "NOTIFY_TAG" => "CRM|DEAL_RESPONSIBLE|" . $ID, "NOTIFY_MESSAGE" => GetMessage("CRM_DEAL_RESPONSIBLE_IM_NOTIFY", array("#title#" => "<a href=\"" . $url . "\" class=\"bx-notifier-item-action\">" . htmlspecialcharsbx($arFields['TITLE']) . "</a>")), "NOTIFY_MESSAGE_OUT" => GetMessage("CRM_DEAL_RESPONSIBLE_IM_NOTIFY", array("#title#" => htmlspecialcharsbx($arFields['TITLE']))) . " (" . $serverName . $url . ")");
                         CIMNotify::Add($arMessageFields);
                     }
                     if ($sonetEvent['TYPE'] == CCrmLiveFeedEvent::Responsible && $sonetEventFields['PARAMS']['START_RESPONSIBLE_ID'] != $modifiedByID) {
                         $arMessageFields = array("MESSAGE_TYPE" => IM_MESSAGE_SYSTEM, "TO_USER_ID" => $sonetEventFields['PARAMS']['START_RESPONSIBLE_ID'], "FROM_USER_ID" => $modifiedByID, "NOTIFY_TYPE" => IM_NOTIFY_FROM, "NOTIFY_MODULE" => "crm", "LOG_ID" => $logEventID, "NOTIFY_EVENT" => "deal_update", "NOTIFY_TAG" => "CRM|DEAL_RESPONSIBLE|" . $ID, "NOTIFY_MESSAGE" => GetMessage("CRM_DEAL_NOT_RESPONSIBLE_IM_NOTIFY", array("#title#" => "<a href=\"" . $url . "\" class=\"bx-notifier-item-action\">" . htmlspecialcharsbx($arFields['TITLE']) . "</a>")), "NOTIFY_MESSAGE_OUT" => GetMessage("CRM_DEAL_NOT_RESPONSIBLE_IM_NOTIFY", array("#title#" => htmlspecialcharsbx($arFields['TITLE']))) . " (" . $serverName . $url . ")");
                         CIMNotify::Add($arMessageFields);
                     }
                     if ($sonetEvent['TYPE'] == CCrmLiveFeedEvent::Progress && $sonetEventFields['PARAMS']['START_STATUS_ID'] && $sonetEventFields['PARAMS']['FINAL_STATUS_ID']) {
                         $assignedByID = isset($arFields['ASSIGNED_BY_ID']) ? $arFields['ASSIGNED_BY_ID'] : $arRow['ASSIGNED_BY_ID'];
                         $infos = CCrmStatus::GetStatus('DEAL_STAGE');
                         if ($assignedByID != $modifiedByID && array_key_exists($sonetEventFields['PARAMS']['START_STATUS_ID'], $infos) && array_key_exists($sonetEventFields['PARAMS']['FINAL_STATUS_ID'], $infos)) {
                             $arMessageFields = array("MESSAGE_TYPE" => IM_MESSAGE_SYSTEM, "TO_USER_ID" => $assignedByID, "FROM_USER_ID" => $modifiedByID, "NOTIFY_TYPE" => IM_NOTIFY_FROM, "NOTIFY_MODULE" => "crm", "LOG_ID" => $logEventID, "NOTIFY_EVENT" => "deal_update", "NOTIFY_TAG" => "CRM|DEAL_PROGRESS|" . $ID, "NOTIFY_MESSAGE" => GetMessage("CRM_DEAL_PROGRESS_IM_NOTIFY", array("#title#" => "<a href=\"" . $url . "\" class=\"bx-notifier-item-action\">" . htmlspecialcharsbx($arFields['TITLE']) . "</a>", "#start_status_title#" => htmlspecialcharsbx($infos[$sonetEventFields['PARAMS']['START_STATUS_ID']]['NAME']), "#final_status_title#" => htmlspecialcharsbx($infos[$sonetEventFields['PARAMS']['FINAL_STATUS_ID']]['NAME']))), "NOTIFY_MESSAGE_OUT" => GetMessage("CRM_DEAL_PROGRESS_IM_NOTIFY", array("#title#" => htmlspecialcharsbx($arFields['TITLE']), "#start_status_title#" => htmlspecialcharsbx($infos[$sonetEventFields['PARAMS']['START_STATUS_ID']]['NAME']), "#final_status_title#" => htmlspecialcharsbx($infos[$sonetEventFields['PARAMS']['FINAL_STATUS_ID']]['NAME']))) . " (" . $serverName . $url . ")");
                             CIMNotify::Add($arMessageFields);
                         }
                     }
                 }
                 unset($sonetEventFields);
             }
             unset($sonetEvent);
         }
         if ($bResult) {
             $afterEvents = GetModuleEvents('crm', 'OnAfterCrmDealUpdate');
             while ($arEvent = $afterEvents->Fetch()) {
                 ExecuteModuleEventEx($arEvent, array(&$arFields));
             }
         }
         self::PullChange('UPDATE', array('ID' => $ID));
     }
     return $bResult;
 }
Exemplo n.º 8
0
    if (!empty($arRes['PHOTO']) && !isset($arFiles[$arRes['PHOTO']])) {
        if ($arFile = CFile::GetFileArray($arRes['PHOTO'])) {
            $arFiles[$arRes['PHOTO']] = CHTTP::URN2URI($arFile['SRC']);
        }
    }
    $arContacts[] = array('id' => $arRes['ID'], 'url' => CComponentEngine::MakePathFromTemplate(COption::GetOptionString('crm', 'path_to_contact_show'), array('contact_id' => $arRes['ID'])), 'title' => str_replace(array(';', ','), ' ', CCrmContact::PrepareFormattedName($arRes)), 'desc' => empty($arRes['COMPANY_TITLE']) ? '' : $arRes['COMPANY_TITLE'], 'image' => isset($arFiles[$arRes['PHOTO']]) ? $arFiles[$arRes['PHOTO']] : '', 'type' => 'contact', 'selected' => false);
}
//CrmLead
$arLeads = array();
$obRes = CCrmLead::GetListEx(array('TITLE' => 'ASC'), array(), false, array('nTopCount' => 50), array('ID', 'TITLE', 'NAME', 'SECOND_NAME', 'LAST_NAME', 'STATUS_ID'));
while ($arRes = $obRes->Fetch()) {
    $arLeads[] = array('id' => $arRes['ID'], 'url' => CComponentEngine::MakePathFromTemplate(COption::GetOptionString('crm', 'path_to_lead_show'), array('lead_id' => $arRes['ID'])), 'title' => str_replace(array(';', ','), ' ', $arRes['TITLE']), 'desc' => CCrmLead::PrepareFormattedName($arRes), 'type' => 'lead', 'selected' => false);
}
//CrmDeal
$arDeals = array();
$obRes = CCrmDeal::GetListEx(array('TITLE' => 'ASC'), array(), false, array('nTopCount' => 50), array('ID', 'TITLE'));
while ($arRes = $obRes->Fetch()) {
    $arDeals[] = array('id' => $arRes['ID'], 'url' => CComponentEngine::MakePathFromTemplate(COption::GetOptionString('crm', 'path_to_deal_show'), array('deal_id' => $arRes['ID'])), 'title' => str_replace(array(';', ','), ' ', $arRes['TITLE']), 'desc' => '', 'type' => 'deal', 'selected' => false);
}
?>

	<script type="text/javascript">
		var crmCompanyElements = <?php 
echo CUtil::PhpToJsObject($arCompanies);
?>
;
		var crmContactElements = <?php 
echo CUtil::PhpToJsObject($arContacts);
?>
;
		var crmLeadElements = <?php 
Exemplo n.º 9
0
 public static function EmailMessageAdd($arMessageFields, $ACTION_VARS)
 {
     if (!CModule::IncludeModule('crm')) {
         return false;
     }
     $date = isset($arMessageFields['FIELD_DATE']) ? $arMessageFields['FIELD_DATE'] : '';
     $maxAgeDays = intval(COption::GetOptionString('crm', 'email_max_age', 7));
     $maxAge = $maxAgeDays > 0 ? $maxAgeDays * 86400 : 0;
     if ($maxAge > 0 && $date !== '') {
         $now = time() + CTimeZone::GetOffset();
         $timestamp = MakeTimeStamp($date, FORMAT_DATETIME);
         if ($now - $timestamp > $maxAge) {
             //Time threshold is exceeded
             return false;
         }
     }
     $crmEmail = strtolower(trim(COption::GetOptionString('crm', 'mail', '')));
     $msgID = isset($arMessageFields['ID']) ? intval($arMessageFields['ID']) : 0;
     $mailboxID = isset($arMessageFields['MAILBOX_ID']) ? intval($arMessageFields['MAILBOX_ID']) : 0;
     $from = isset($arMessageFields['FIELD_FROM']) ? $arMessageFields['FIELD_FROM'] : '';
     $replyTo = isset($arMessageFields['FIELD_REPLY_TO']) ? $arMessageFields['FIELD_REPLY_TO'] : '';
     if ($replyTo !== '') {
         // Ignore FROM if REPLY_TO EXISTS
         $from = $replyTo;
     }
     $addresserInfo = CCrmMailHelper::ParseEmail($from);
     if ($crmEmail !== '' && strcasecmp($addresserInfo['EMAIL'], $crmEmail) === 0) {
         // Ignore emails from ourselves
         return false;
     }
     $to = isset($arMessageFields['FIELD_TO']) ? $arMessageFields['FIELD_TO'] : '';
     $cc = isset($arMessageFields['FIELD_CC']) ? $arMessageFields['FIELD_CC'] : '';
     $bcc = isset($arMessageFields['FIELD_BCC']) ? $arMessageFields['FIELD_BCC'] : '';
     $addresseeEmails = array_unique(array_merge($to !== '' ? CMailUtil::ExtractAllMailAddresses($to) : array(), $cc !== '' ? CMailUtil::ExtractAllMailAddresses($cc) : array(), $bcc !== '' ? CMailUtil::ExtractAllMailAddresses($bcc) : array()), SORT_STRING);
     if ($mailboxID > 0) {
         $dbMailbox = CMailBox::GetById($mailboxID);
         $arMailbox = $dbMailbox->Fetch();
         // POP3 mailboxes are ignored - they bound to single email
         if ($arMailbox && $arMailbox['SERVER_TYPE'] === 'smtp' && (empty($crmEmail) || !in_array($crmEmail, $addresseeEmails, true))) {
             return false;
         }
     }
     $subject = isset($arMessageFields['SUBJECT']) ? $arMessageFields['SUBJECT'] : '';
     $body = isset($arMessageFields['BODY']) ? $arMessageFields['BODY'] : '';
     $arBodyEmails = null;
     $userID = 0;
     $parentID = 0;
     $ownerTypeID = CCrmOwnerType::Undefined;
     $ownerID = 0;
     $addresserID = self::FindUserIDByEmail($addresserInfo['EMAIL']);
     if ($addresserID > 0 && Bitrix\Crm\Integration\IntranetManager::isExternalUser($addresserID)) {
         //Forget about extranet user
         $addresserID = 0;
     }
     $arCommEmails = $addresserID <= 0 ? array($addresserInfo['EMAIL']) : ($crmEmail !== '' ? array_diff($addresseeEmails, array($crmEmail)) : $addresseeEmails);
     //Trying to fix strange behaviour of array_diff under OPcache (issue #60862)
     $arCommEmails = array_filter($arCommEmails);
     $targInfo = CCrmActivity::ParseUrn(CCrmActivity::ExtractUrnFromMessage($arMessageFields, CCrmEMailCodeAllocation::GetCurrent()));
     $targActivity = $targInfo['ID'] > 0 ? CCrmActivity::GetByID($targInfo['ID'], false) : null;
     // Check URN
     if (!$targActivity && (!isset($targActivity['URN']) || strtoupper($targActivity['URN']) !== strtoupper($targInfo['URN']))) {
         $targActivity = null;
     }
     if ($targActivity) {
         $postingID = self::ExtractPostingID($arMessageFields);
         if ($postingID > 0 && isset($targActivity['ASSOCIATED_ENTITY_ID']) && intval($targActivity['ASSOCIATED_ENTITY_ID']) === $postingID) {
             // Ignore - it is our message.
             return false;
         }
         $parentID = $targActivity['ID'];
         $subject = CCrmActivity::ClearUrn($subject);
         if ($addresserID > 0) {
             $userID = $addresserID;
         } elseif (isset($targActivity['RESPONSIBLE_ID'])) {
             $userID = $targActivity['RESPONSIBLE_ID'];
         }
         if (isset($targActivity['OWNER_TYPE_ID'])) {
             $ownerTypeID = intval($targActivity['OWNER_TYPE_ID']);
         }
         if (isset($targActivity['OWNER_ID'])) {
             $ownerID = intval($targActivity['OWNER_ID']);
         }
         $arCommData = self::ExtractCommsFromEmails($arCommEmails);
         if ($ownerTypeID > 0 && $ownerID > 0) {
             if (empty($arCommData)) {
                 if ($addresserID > 0) {
                     foreach ($addresseeEmails as $email) {
                         if ($email === $crmEmail) {
                             continue;
                         }
                         $arCommData = array(self::CreateComm($ownerTypeID, $ownerID, $email));
                     }
                 } else {
                     $arCommData = array(self::CreateComm($ownerTypeID, $ownerID, $addresserInfo['EMAIL']));
                 }
             } elseif ($ownerTypeID !== CCrmOwnerType::Deal) {
                 //Check if owner in communications. Otherwise clear owner.
                 //There is only one exception for DEAL - it entity has no communications
                 $isOwnerInComms = false;
                 foreach ($arCommData as &$arCommItem) {
                     $commEntityTypeID = isset($arCommItem['ENTITY_TYPE_ID']) ? $arCommItem['ENTITY_TYPE_ID'] : CCrmOwnerType::Undefined;
                     $commEntityID = isset($arCommItem['ENTITY_ID']) ? $arCommItem['ENTITY_ID'] : 0;
                     if ($commEntityTypeID === $ownerTypeID && $commEntityID === $ownerID) {
                         $isOwnerInComms = true;
                         break;
                     }
                 }
                 unset($arCommItem);
                 if (!$isOwnerInComms) {
                     $ownerTypeID = CCrmOwnerType::Undefined;
                     $ownerID = 0;
                 }
             }
         }
     } else {
         if ($addresserID > 0) {
             //It is email from registred user
             $userID = $addresserID;
             if (empty($arCommEmails)) {
                 $arBodyEmails = self::ExtractEmailsFromBody($body);
                 //Clear system user emails
                 if (!empty($arBodyEmails)) {
                     foreach ($arBodyEmails as $email) {
                         if (self::FindUserIDByEmail($email) <= 0) {
                             $arCommEmails[] = $email;
                         }
                     }
                 }
             }
             // Try to resolve communications
             $arCommData = self::ExtractCommsFromEmails($arCommEmails);
         } else {
             //It is email from unknown user
             //Try to resolve bindings from addresser
             $arCommData = self::ExtractCommsFromEmails($arCommEmails);
             if (!empty($arCommData)) {
                 // Try to resolve responsible user
                 foreach ($arCommData as &$arComm) {
                     $userID = self::ResolveResponsibleID($arComm['ENTITY_TYPE_ID'], $arComm['ENTITY_ID']);
                     if ($userID > 0) {
                         break;
                     }
                 }
                 unset($arComm);
             }
         }
         // Try to resolve owner by old-style method-->
         $arACTION_VARS = explode('&', $ACTION_VARS);
         for ($i = 0, $ic = count($arACTION_VARS); $i < $ic; $i++) {
             $v = $arACTION_VARS[$i];
             if ($pos = strpos($v, '=')) {
                 $name = substr($v, 0, $pos);
                 ${$name} = urldecode(substr($v, $pos + 1));
             }
         }
         $arTypeNames = CCrmOwnerType::GetNames(array(CCrmOwnerType::Lead, CCrmOwnerType::Deal, CCrmOwnerType::Contact, CCrmOwnerType::Company));
         foreach ($arTypeNames as $typeName) {
             $regexVar = 'W_CRM_ENTITY_REGEXP_' . $typeName;
             if (empty(${$regexVar})) {
                 continue;
             }
             $match = array();
             if (preg_match('/' . ${$regexVar} . '/i' . BX_UTF_PCRE_MODIFIER, $subject, $match) === 1) {
                 $ownerID = intval($match[1]);
                 $ownerTypeID = CCrmOwnerType::ResolveID($typeName);
                 break;
             }
         }
         // <-- Try to resolve owner by old-style method
         // Filter communications by owner
         if ($ownerTypeID > 0 && $ownerID > 0) {
             if (!empty($arCommData)) {
                 foreach ($arCommData as $commKey => $arComm) {
                     if ($arComm['ENTITY_TYPE_ID'] === $ownerTypeID && $arComm['ENTITY_ID'] === $ownerID) {
                         continue;
                     }
                     unset($arCommData[$commKey]);
                 }
                 $arCommData = array_values($arCommData);
             }
             if (empty($arCommData)) {
                 if ($addresserID > 0) {
                     foreach ($addresseeEmails as $email) {
                         if ($email === $crmEmail) {
                             continue;
                         }
                         $arCommData = array(self::CreateComm($ownerTypeID, $ownerID, $email));
                     }
                 } else {
                     $arCommData = array(self::CreateComm($ownerTypeID, $ownerID, $addresserInfo['EMAIL']));
                 }
             }
         }
     }
     $arBindingData = self::ConvertCommsToBindings($arCommData);
     // Check bindings for converted leads -->
     // Not Existed entities are ignored. Converted leads are ignored if their associated entities (contacts, companies, deals) are contained in bindings.
     $arCorrectedBindingData = array();
     $arConvertedLeadData = array();
     foreach ($arBindingData as $bindingKey => &$arBinding) {
         if ($arBinding['TYPE_ID'] !== CCrmOwnerType::Lead) {
             if (self::IsEntityExists($arBinding['TYPE_ID'], $arBinding['ID'])) {
                 $arCorrectedBindingData[$bindingKey] = $arBinding;
             }
             continue;
         }
         $arFields = self::GetEntity(CCrmOwnerType::Lead, $arBinding['ID'], array('STATUS_ID'));
         if (!is_array($arFields)) {
             continue;
         }
         if (isset($arFields['STATUS_ID']) && $arFields['STATUS_ID'] === 'CONVERTED') {
             $arConvertedLeadData[$bindingKey] = $arBinding;
         } else {
             $arCorrectedBindingData[$bindingKey] = $arBinding;
         }
     }
     unset($arBinding);
     foreach ($arConvertedLeadData as &$arConvertedLead) {
         $leadID = $arConvertedLead['ID'];
         $exists = false;
         $dbRes = CCrmCompany::GetListEx(array(), array('LEAD_ID' => $leadID, 'CHECK_PERMISSIONS' => 'N'), false, false, array('ID'));
         if ($dbRes) {
             while ($arRes = $dbRes->Fetch()) {
                 if (isset($arCorrectedBindingData[self::PrepareEntityKey(CCrmOwnerType::Company, $arRes['ID'])])) {
                     $exists = true;
                     break;
                 }
             }
         }
         if ($exists) {
             continue;
         }
         $dbRes = CCrmContact::GetListEx(array(), array('LEAD_ID' => $leadID, 'CHECK_PERMISSIONS' => 'N'), false, false, array('ID'));
         if ($dbRes) {
             while ($arRes = $dbRes->Fetch()) {
                 if (isset($arCorrectedBindingData[self::PrepareEntityKey(CCrmOwnerType::Contact, $arRes['ID'])])) {
                     $exists = true;
                     break;
                 }
             }
         }
         if ($exists) {
             continue;
         }
         $dbRes = CCrmDeal::GetListEx(array(), array('LEAD_ID' => $leadID, 'CHECK_PERMISSIONS' => 'N'), false, false, array('ID'));
         if ($dbRes) {
             while ($arRes = $dbRes->Fetch()) {
                 if (isset($arCorrectedBindingData[self::PrepareEntityKey(CCrmOwnerType::Deal, $arRes['ID'])])) {
                     $exists = true;
                     break;
                 }
             }
         }
         if ($exists) {
             continue;
         }
         $arCorrectedBindingData[self::PrepareEntityKey(CCrmOwnerType::Lead, $leadID)] = $arConvertedLead;
     }
     unset($arConvertedLead);
     $arBindingData = $arCorrectedBindingData;
     // <-- Check bindings for converted leads
     // If no bindings are found then create new lead from this message
     // Skip lead creation if email list is empty. Otherwise we will create lead with no email-addresses. It is absolutely useless.
     $emailQty = count($arCommEmails);
     if (empty($arBindingData) && $emailQty > 0) {
         if (strtoupper(COption::GetOptionString('crm', 'email_create_lead_for_new_addresser', 'Y')) !== 'Y') {
             // Creation of new lead is not allowed
             return true;
         }
         //"Lead from forwarded email..." or "Lead from email..."
         $title = $subject !== '' ? $subject : GetMessage($addresserID > 0 ? 'CRM_MAIL_LEAD_FROM_USER_EMAIL_TITLE' : 'CRM_MAIL_LEAD_FROM_EMAIL_TITLE', array('%SENDER%' => $addresserInfo['ORIGINAL']));
         $comment = '';
         if ($body !== '') {
             // Remove extra new lines (fix for #31807)
             $comment = preg_replace("/(\r\n|\n|\r)+/", '<br/>', htmlspecialcharsbx($body));
         }
         if ($comment === '') {
             $comment = htmlspecialcharsbx($subject);
         }
         $name = '';
         if ($addresserID <= 0) {
             $name = $addresserInfo['NAME'];
         } else {
             //Try get name from body
             for ($i = 0; $i < $emailQty; $i++) {
                 $email = $arCommEmails[$i];
                 $match = array();
                 if (preg_match('/"([^"]+)"\\s*<' . $email . '>/i' . BX_UTF_PCRE_MODIFIER, $body, $match) === 1 && count($match) > 1) {
                     $name = $match[1];
                     break;
                 }
                 if (preg_match('/"([^"]+)"\\s*[\\s*mailto\\:\\s*' . $email . ']/i' . BX_UTF_PCRE_MODIFIER, $body, $match) === 1 && count($match) > 1) {
                     $name = $match[1];
                     break;
                 }
             }
             if ($name === '') {
                 $name = $arCommEmails[0];
             }
         }
         $arLeadFields = array('TITLE' => $title, 'NAME' => $name, 'STATUS_ID' => 'NEW', 'COMMENTS' => $comment, 'SOURCE_DESCRIPTION' => GetMessage('CRM_MAIL_LEAD_FROM_EMAIL_SOURCE', array('%SENDER%' => $addresserInfo['ORIGINAL'])), 'OPENED' => 'Y', 'FM' => array('EMAIL' => array()));
         $sourceList = CCrmStatus::GetStatusList('SOURCE');
         $sourceID = COption::GetOptionString('crm', 'email_lead_source_id', '');
         if ($sourceID === '' || !isset($sourceList[$sourceID])) {
             if (isset($sourceList['EMAIL'])) {
                 $sourceID = 'EMAIL';
             } elseif (isset($sourceList['OTHER'])) {
                 $sourceID = 'OTHER';
             }
         }
         if ($sourceID !== '') {
             $arLeadFields['SOURCE_ID'] = $sourceID;
         }
         $responsibleID = intval(COption::GetOptionString('crm', 'email_lead_responsible_id', 0));
         if ($responsibleID > 0) {
             $arLeadFields['CREATED_BY_ID'] = $arLeadFields['MODIFY_BY_ID'] = $arLeadFields['ASSIGNED_BY_ID'] = $responsibleID;
             if ($userID === 0) {
                 $userID = $responsibleID;
             }
         }
         for ($i = 0; $i < $emailQty; $i++) {
             $arLeadFields['FM']['EMAIL']['n' . ($i + 1)] = array('VALUE_TYPE' => 'WORK', 'VALUE' => $arCommEmails[$i]);
         }
         $leadEntity = new CCrmLead(false);
         $leadID = $leadEntity->Add($arLeadFields, true, array('DISABLE_USER_FIELD_CHECK' => true, 'REGISTER_SONET_EVENT' => true, 'CURRENT_USER' => $responsibleID));
         // TODO: log error
         if ($leadID > 0) {
             $arBizProcErrors = array();
             CCrmBizProcHelper::AutoStartWorkflows(CCrmOwnerType::Lead, $leadID, CCrmBizProcEventType::Create, $arBizProcErrors);
             $arCommData = array();
             for ($i = 0; $i < $emailQty; $i++) {
                 $arCommData[] = self::CreateComm(CCrmOwnerType::Lead, $leadID, $arCommEmails[$i]);
             }
             $arBindingData = array(self::PrepareEntityKey(CCrmOwnerType::Lead, $leadID) => self::CreateBinding(CCrmOwnerType::Lead, $leadID));
         }
     }
     // Terminate processing if no bindings are found.
     if (empty($arBindingData)) {
         // Try to export vcf-files before exit if email from registered user
         if ($addresserID > 0) {
             $dbAttachment = CMailAttachment::GetList(array(), array('MESSAGE_ID' => $msgID));
             while ($arAttachment = $dbAttachment->Fetch()) {
                 if (GetFileExtension(strtolower($arAttachment['FILE_NAME'])) === 'vcf') {
                     if ($arAttachment['FILE_ID']) {
                         $arAttachment['FILE_DATA'] = CMailAttachment::getContents($arAttachment);
                     }
                     self::TryImportVCard($arAttachment['FILE_DATA']);
                 }
             }
         }
         return false;
     }
     // If owner info not defined set it by default
     if ($ownerID <= 0 || $ownerTypeID <= 0) {
         if (count($arBindingData) > 1) {
             // Search owner in specified order: Contact, Company, Lead.
             $arTypeIDs = array(CCrmOwnerType::Contact, CCrmOwnerType::Company, CCrmOwnerType::Lead);
             foreach ($arTypeIDs as $typeID) {
                 foreach ($arBindingData as &$arBinding) {
                     if ($arBinding['TYPE_ID'] === $typeID) {
                         $ownerTypeID = $typeID;
                         $ownerID = $arBinding['ID'];
                         break;
                     }
                 }
                 unset($arBinding);
                 if ($ownerID > 0 && $ownerTypeID > 0) {
                     break;
                 }
             }
         }
         if ($ownerID <= 0 || $ownerTypeID <= 0) {
             $arBinding = array_shift(array_values($arBindingData));
             $ownerTypeID = $arBinding['TYPE_ID'];
             $ownerID = $arBinding['ID'];
         }
     }
     // Precessing of attachments -->
     $attachmentMaxSizeMb = intval(COption::GetOptionString('crm', 'email_attachment_max_size', 16));
     $attachmentMaxSize = $attachmentMaxSizeMb > 0 ? $attachmentMaxSizeMb * 1048576 : 0;
     $arFilesData = array();
     $dbAttachment = CMailAttachment::GetList(array(), array('MESSAGE_ID' => $msgID));
     $arBannedAttachments = array();
     while ($arAttachment = $dbAttachment->Fetch()) {
         if ($arAttachment['FILE_NAME'] === '1.tmp') {
             // HACK: For bug in module 'Mail'
             continue;
         } elseif (GetFileExtension(strtolower($arAttachment['FILE_NAME'])) === 'vcf') {
             if ($arAttachment['FILE_ID']) {
                 $arAttachment['FILE_DATA'] = CMailAttachment::getContents($arAttachment);
             }
             self::TryImportVCard($arAttachment['FILE_DATA']);
         }
         $fileSize = isset($arAttachment['FILE_SIZE']) ? intval($arAttachment['FILE_SIZE']) : 0;
         if ($fileSize <= 0) {
             //Skip zero lenth files
             continue;
         }
         if ($attachmentMaxSize > 0 && $fileSize > $attachmentMaxSize) {
             //File size limit  is exceeded
             $arBannedAttachments[] = array('name' => $arAttachment['FILE_NAME'], 'size' => $fileSize);
             continue;
         }
         if ($arAttachment['FILE_ID'] && empty($arAttachment['FILE_DATA'])) {
             $arAttachment['FILE_DATA'] = CMailAttachment::getContents($arAttachment);
         }
         $arFilesData[] = array('name' => $arAttachment['FILE_NAME'], 'type' => $arAttachment['CONTENT_TYPE'], 'content' => $arAttachment['FILE_DATA'], 'MODULE_ID' => 'crm');
     }
     //<-- Precessing of attachments
     // Remove extra new lines (fix for #31807)
     $body = preg_replace("/(\r\n|\n|\r)+/", PHP_EOL, $body);
     $encodedBody = htmlspecialcharsbx($body);
     // Creating of new event -->
     $arEventBindings = array();
     foreach ($arBindingData as &$arBinding) {
         $arEventBindings[] = array('ENTITY_TYPE' => $arBinding['TYPE_NAME'], 'ENTITY_ID' => $arBinding['ID']);
     }
     unset($arBinding);
     $eventText = '';
     $eventText .= '<b>' . GetMessage('CRM_EMAIL_SUBJECT') . '</b>: ' . $subject . PHP_EOL;
     $eventText .= '<b>' . GetMessage('CRM_EMAIL_FROM') . '</b>: ' . $addresserInfo['EMAIL'] . PHP_EOL;
     $eventText .= '<b>' . GetMessage('CRM_EMAIL_TO') . '</b>: ' . implode($addresseeEmails, '; ') . PHP_EOL;
     if (!empty($arBannedAttachments)) {
         $eventText .= '<b>' . GetMessage('CRM_EMAIL_BANNENED_ATTACHMENTS', array('%MAX_SIZE%' => $attachmentMaxSizeMb)) . '</b>: ';
         foreach ($arBannedAttachments as &$attachmentInfo) {
             $eventText .= GetMessage('CRM_EMAIL_BANNENED_ATTACHMENT_INFO', array('%NAME%' => $attachmentInfo['name'], '%SIZE%' => round($attachmentInfo['size'] / 1048576, 1)));
         }
         unset($attachmentInfo);
         $eventText .= PHP_EOL;
     }
     $eventText .= $encodedBody;
     $CCrmEvent = new CCrmEvent();
     $CCrmEvent->Add(array('USER_ID' => $userID, 'ENTITY' => array_values($arEventBindings), 'ENTITY_TYPE' => CCrmOwnerType::ResolveName($ownerTypeID), 'ENTITY_ID' => $ownerID, 'EVENT_NAME' => GetMessage('CRM_EMAIL_GET_EMAIL'), 'EVENT_TYPE' => 2, 'EVENT_TEXT_1' => $eventText, 'FILES' => $arFilesData), false);
     // <-- Creating of new event
     // Creating new activity -->
     $siteID = '';
     $dbSites = CSite::GetList($by = 'sort', $order = 'desc', array('DEFAULT' => 'Y', 'ACTIVE' => 'Y'));
     $defaultSite = is_object($dbSites) ? $dbSites->Fetch() : null;
     if (is_array($defaultSite)) {
         $siteID = $defaultSite['LID'];
     }
     if ($siteID === '') {
         $siteID = 's1';
     }
     $storageTypeID = CCrmActivity::GetDefaultStorageTypeID();
     $arElementIDs = array();
     foreach ($arFilesData as $fileData) {
         $fileID = CFile::SaveFile($fileData, 'crm');
         if ($fileID > 0) {
             $elementID = StorageManager::saveEmailAttachment(CFile::GetFileArray($fileID), $storageTypeID, $siteID);
             if ($elementID > 0) {
                 $arElementIDs[] = (int) $elementID;
             }
         }
     }
     $descr = preg_replace("/(\r\n|\n|\r)+/", '<br/>', $encodedBody);
     $now = ConvertTimeStamp(time() + CTimeZone::GetOffset(), 'FULL', $siteID);
     $direction = CCrmActivityDirection::Incoming;
     $completed = 'N';
     // Incomming emails must be marked as 'Not Completed'.
     if ($addresserID > 0 && ActivitySettings::getValue(ActivitySettings::MARK_FORWARDED_EMAIL_AS_OUTGOING)) {
         $direction = CCrmActivityDirection::Outgoing;
         $completed = 'Y';
     }
     $arActivityFields = array('OWNER_ID' => $ownerID, 'OWNER_TYPE_ID' => $ownerTypeID, 'TYPE_ID' => CCrmActivityType::Email, 'ASSOCIATED_ENTITY_ID' => 0, 'PARENT_ID' => $parentID, 'SUBJECT' => $subject, 'START_TIME' => $now, 'END_TIME' => $now, 'COMPLETED' => $completed, 'AUTHOR_ID' => $userID, 'RESPONSIBLE_ID' => $userID, 'PRIORITY' => CCrmActivityPriority::Medium, 'DESCRIPTION' => $descr, 'DESCRIPTION_TYPE' => CCrmContentType::Html, 'DIRECTION' => $direction, 'LOCATION' => '', 'NOTIFY_TYPE' => CCrmActivityNotifyType::None, 'STORAGE_TYPE_ID' => $storageTypeID, 'STORAGE_ELEMENT_IDS' => $arElementIDs);
     $arActivityFields['BINDINGS'] = array();
     foreach ($arBindingData as &$arBinding) {
         $entityTypeID = $arBinding['TYPE_ID'];
         $entityID = $arBinding['ID'];
         if ($entityTypeID <= 0 || $entityID <= 0) {
             continue;
         }
         $arActivityFields['BINDINGS'][] = array('OWNER_TYPE_ID' => $entityTypeID, 'OWNER_ID' => $entityID);
     }
     unset($arBinding);
     $activityID = CCrmActivity::Add($arActivityFields, false, false, array('REGISTER_SONET_EVENT' => true));
     if ($activityID > 0 && !empty($arCommData)) {
         CCrmActivity::SaveCommunications($activityID, $arCommData, $arActivityFields, false, false);
         $arActivityFields['COMMUNICATIONS'] = $arCommData;
     }
     //Notity responsible user
     if ($userID > 0 && $direction === CCrmActivityDirection::Incoming) {
         CCrmActivity::Notify($arActivityFields, CCrmNotifierSchemeType::IncomingEmail);
     }
     // <-- Creating new activity
     return true;
 }
Exemplo n.º 10
0
        $arResult['DEAL'][$arDeal['ID']] = $arDeal;
        $arResult['DEAL_ID'][$arDeal['ID']] = $arDeal['ID'];
        $arResult['DEAL_UF'][$arDeal['ID']] = array();
    }
} else {
    $navDbResult = CCrmActivity::GetEntityList(CCrmOwnerType::Deal, $userID, $arSort['nearest_activity'], $arFilter, !$isInExportMode ? $arNavParams : false);
    $arResult['ROWS_COUNT'] = $navDbResult->SelectedRowsCount();
    $arResult['DB_LIST'] = $navDbResult;
    $arResult['DB_FILTER'] = $arFilter;
    while ($arDeal = $navDbResult->Fetch()) {
        $arResult['DEAL'][$arDeal['ID']] = $arDeal;
        $arResult['DEAL_ID'][$arDeal['ID']] = $arDeal['ID'];
        $arResult['DEAL_UF'][$arDeal['ID']] = array();
    }
    $arFilter['@ID'] = array_keys($arResult['DEAL']);
    $dbResult = CCrmDeal::GetListEx($arSort, $arFilter, false, false, $arSelect, $arOptions);
    while ($arDeal = $dbResult->GetNext()) {
        $arResult['DEAL'][$arDeal['ID']] = $arDeal;
    }
}
$now = time() + CTimeZone::GetOffset();
foreach ($arResult['DEAL'] as &$arDeal) {
    $arDeal['CLOSEDATE'] = !empty($arDeal['CLOSEDATE']) ? CCrmComponentHelper::TrimDateTimeString(ConvertTimeStamp(MakeTimeStamp($arDeal['CLOSEDATE']), 'SHORT', SITE_ID)) : '';
    $arDeal['BEGINDATE'] = !empty($arDeal['BEGINDATE']) ? CCrmComponentHelper::TrimDateTimeString(ConvertTimeStamp(MakeTimeStamp($arDeal['BEGINDATE']), 'SHORT', SITE_ID)) : '';
    $arDeal['EVENT_DATE'] = !empty($arDeal['EVENT_DATE']) ? CCrmComponentHelper::TrimDateTimeString(ConvertTimeStamp(MakeTimeStamp($arDeal['EVENT_DATE']), 'SHORT', SITE_ID)) : '';
    $arDeal['~CLOSEDATE'] = $arDeal['CLOSEDATE'];
    $arDeal['~BEGINDATE'] = $arDeal['BEGINDATE'];
    $arDeal['~EVENT_DATE'] = $arDeal['EVENT_DATE'];
    $currencyID = isset($arDeal['~CURRENCY_ID']) ? $arDeal['~CURRENCY_ID'] : CCrmCurrency::GetBaseCurrencyID();
    $arDeal['~CURRENCY_ID'] = $currencyID;
    $arDeal['CURRENCY_ID'] = htmlspecialcharsbx($currencyID);
Exemplo n.º 11
0
             continue;
         }
         $entityTypeName = strtoupper($commInfo[0]);
         $entityTypeID = CCrmOwnerType::ResolveID($entityTypeName);
         $entityID = intval($commInfo[1]);
         if (!CCrmOwnerType::IsDefined($entityTypeID) || $entityID <= 0 || !CCrmActivity::CheckUpdatePermission($entityTypeID, $entityID, $userPerms)) {
             continue;
         }
         $commValue = CCrmActivity::GetDefaultCommunicationValue($entityTypeID, $entityID, $commType);
         if ($commValue !== '') {
             $comms[] = array('TYPE' => $commType, 'VALUE' => $commValue, 'ENTITY_TYPE_ID' => $entityTypeID, 'ENTITY_ID' => $entityID);
         }
     }
 }
 if (empty($comms)) {
     $dbDeal = CCrmDeal::GetListEx(array(), array('=ID' => $ownerID, 'CHECK_PERMISSIONS' => 'N'), false, false, array('CONTACT_ID', 'CONTACT_NAME', 'CONTACT_SECOND_NAME', 'CONTACT_LAST_NAME', 'COMPANY_ID', 'COMPANY_TITLE'));
     $deal = $dbDeal->Fetch();
     if (is_array($deal)) {
         $contactID = isset($deal['CONTACT_ID']) ? intval($deal['CONTACT_ID']) : 0;
         $companyID = isset($deal['COMPANY_ID']) ? intval($deal['COMPANY_ID']) : 0;
         $comms = array();
         if ($contactID > 0 && CCrmActivity::CheckUpdatePermission(CCrmOwnerType::Contact, $contactID, $userPerms)) {
             $commValue = CCrmActivity::GetDefaultCommunicationValue(CCrmOwnerType::Contact, $contactID, $commType);
             if ($commValue !== '') {
                 $comms[] = array('TYPE' => $commType, 'VALUE' => $commValue, 'ENTITY_TYPE_ID' => CCrmOwnerType::Contact, 'ENTITY_ID' => $contactID, 'ENTITY_SETTINGS' => array('NAME' => isset($deal['CONTACT_NAME']) ? $deal['CONTACT_NAME'] : '', 'SECOND_NAME' => isset($deal['CONTACT_SECOND_NAME']) ? $deal['CONTACT_SECOND_NAME'] : '', 'LAST_NAME' => isset($deal['CONTACT_LAST_NAME']) ? $deal['CONTACT_LAST_NAME'] : ''));
             }
         }
         if (empty($comms) && $companyID > 0 && CCrmActivity::CheckUpdatePermission(CCrmOwnerType::Company, $companyID, $userPerms)) {
             $commValue = CCrmActivity::GetDefaultCommunicationValue(CCrmOwnerType::Company, $companyID, $commType);
             if ($commValue !== '') {
                 $comms[] = array('TYPE' => $commType, 'VALUE' => $commValue, 'ENTITY_TYPE_ID' => CCrmOwnerType::Company, 'ENTITY_ID' => $companyID, 'ENTITY_SETTINGS' => array('COMPANY_TITLE' => isset($deal['COMPANY_TITLE']) ? $deal['COMPANY_TITLE'] : ''));
Exemplo n.º 12
0
 $now = time() + CTimeZone::GetOffset();
 $nowDate = ConvertTimeStamp($now, 'SHORT', SITE_ID);
 $arFields = array('~CURRENCY' => $currencyID, 'CURRENCY' => htmlspecialcharsbx($currencyID));
 $arFields['~STATUS_ID'] = !empty($arResult['STATUS_LIST']) ? array_shift(array_keys($arResult['STATUS_LIST'])) : '';
 $arFields['STATUS_ID'] = htmlspecialcharsbx($arFields['~STATUS_ID']);
 $arFields['DATE_PAY_BEFORE_STAMP'] = 0;
 $arFields['~DATE_PAY_BEFORE'] = $arFields['DATE_PAY_BEFORE'] = '';
 $arFields['DATE_BILL_STAMP'] = $now;
 $arFields['~DATE_BILL'] = $arFields['~DATE_INSERT'] = $nowDate;
 $arFields['DATE_BILL'] = $arFields['DATE_INSERT'] = htmlspecialcharsbx($nowDate);
 if (isset($_REQUEST['deal_id'])) {
     $dealID = max(intval($_REQUEST['deal_id']), 0);
 }
 if ($dealID > 0) {
     $arFields['~UF_DEAL_ID'] = $arFields['UF_DEAL_ID'] = $dealID;
     $dbDeal = CCrmDeal::GetListEx(array(), array('=ID' => $dealID), false, false, array('ID', 'COMPANY_ID', 'CONTACT_ID', 'CURRENCY_ID', 'ASSIGNED_BY_ID', 'TITLE', 'COMMENTS'));
     $deal = $dbDeal ? $dbDeal->Fetch() : null;
     if (is_array($deal)) {
         $companyID = $arFields['~UF_COMPANY_ID'] = $arFields['UF_COMPANY_ID'] = isset($deal['COMPANY_ID']) ? intval($deal['COMPANY_ID']) : 0;
         $contactID = $arFields['~UF_CONTACT_ID'] = $arFields['UF_CONTACT_ID'] = isset($deal['CONTACT_ID']) ? intval($deal['CONTACT_ID']) : 0;
         $dealCurrencyID = isset($deal['CURRENCY_ID']) ? $deal['CURRENCY_ID'] : CCrmCurrency::GetBaseCurrencyID();
         $arFields['~ORDER_TOPIC'] = isset($deal['TITLE']) ? $deal['TITLE'] : '';
         $arFields['ORDER_TOPIC'] = htmlspecialcharsbx($arFields['~ORDER_TOPIC']);
         $arFields['~USER_DESCRIPTION'] = isset($deal['COMMENTS']) ? $deal['COMMENTS'] : '';
         $arFields['USER_DESCRIPTION'] = htmlspecialcharsbx($arFields['~USER_DESCRIPTION']);
         $arFields['~RESPONSIBLE_ID'] = $arFields['RESPONSIBLE_ID'] = isset($deal['ASSIGNED_BY_ID']) ? intval($deal['ASSIGNED_BY_ID']) : 0;
     }
 } else {
     if (isset($_REQUEST['company_id'])) {
         $companyID = max(intval($_REQUEST['company_id']), 0);
     }
 /**
  * @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');
     }
     if (!is_array($entityFields)) {
         $dbResult = \CCrmDeal::GetListEx(array(), array('=ID' => $ownerID, 'CHECK_PERMISSIONS' => 'N'), false, false, array('STAGE_ID', 'ASSIGNED_BY_ID', 'BEGINDATE', 'CLOSEDATE', 'OPPORTUNITY', 'CURRENCY_ID'));
         $entityFields = is_object($dbResult) ? $dbResult->Fetch() : null;
         if (!is_array($entityFields)) {
             return false;
         }
     }
     $stageID = isset($entityFields['STAGE_ID']) ? $entityFields['STAGE_ID'] : '';
     $semanticID = \CCrmDeal::GetSemanticID($stageID);
     $isLost = PhaseSemantics::isLost($semanticID);
     $responsibleID = isset($entityFields['ASSIGNED_BY_ID']) ? (int) $entityFields['ASSIGNED_BY_ID'] : 0;
     /** @var Date $startDate */
     $startDate = self::parseDateString(isset($entityFields['BEGINDATE']) ? $entityFields['BEGINDATE'] : '');
     if ($startDate === null) {
         $startDate = new Date();
     }
     /** @var Date $endDate */
     $endDate = self::parseDateString(isset($entityFields['CLOSEDATE']) ? $entityFields['CLOSEDATE'] : '');
     if ($endDate === null) {
         $endDate = new Date('9999-12-31', 'Y-m-d');
     }
     $sum = isset($entityFields['OPPORTUNITY']) ? (double) $entityFields['OPPORTUNITY'] : 0.0;
     $currencyID = isset($entityFields['CURRENCY_ID']) ? $entityFields['CURRENCY_ID'] : '';
     if ($currencyID === '') {
         $currencyID = \CCrmCurrency::GetBaseCurrencyID();
     }
     $accountCurrencyID = \CCrmCurrency::GetAccountCurrencyID();
     $sumData = \CCrmAccountingHelper::PrepareAccountingData(array('CURRENCY_ID' => $currencyID, 'SUM' => $sum));
     if (is_array($sumData)) {
         $sum = (double) $sumData['ACCOUNT_SUM'];
     }
     $latest = self::getLatest($ownerID);
     if (!is_array($latest)) {
         if ($semanticID === PhaseSemantics::SUCCESS) {
             //Creation of stub for successfully completed entity without invoices
             self::innerRegister(array('OWNER_ID' => $ownerID, 'CREATED_DATE' => new Date(), 'START_DATE' => $startDate, 'END_DATE' => $endDate, 'RESPONSIBLE_ID' => $responsibleID, 'STAGE_SEMANTIC_ID' => PhaseSemantics::SUCCESS, 'STAGE_ID' => $stageID, 'IS_LOST' => 'N', 'CURRENCY_ID' => $accountCurrencyID, 'INVOICE_SUM' => 0.0, 'INVOICE_QTY' => 0, 'TOTAL_INVOICE_SUM' => 0.0, 'TOTAL_INVOICE_QTY' => 0, 'TOTAL_SUM' => $sum));
         }
         return true;
     }
     if ($startDate->getTimestamp() === $latest['START_DATE']->getTimestamp() && $endDate->getTimestamp() === $latest['END_DATE']->getTimestamp() && $responsibleID === (int) $latest['RESPONSIBLE_ID'] && $stageID === $latest['STAGE_ID'] && $semanticID === $latest['STAGE_SEMANTIC_ID'] && $sum === (double) $latest['TOTAL_SUM']) {
         return false;
     }
     if ($semanticID !== $latest['STAGE_SEMANTIC_ID'] && $latest['STAGE_SEMANTIC_ID'] === PhaseSemantics::SUCCESS && (int) $latest['INVOICE_QTY'] === 0) {
         //Clean up stub for successfully completed entity without invoices
         DealInvoiceStatisticsTable::delete(array('OWNER_ID' => $ownerID, 'CREATED_DATE' => $latest['CREATED_DATE']));
     } else {
         DealInvoiceStatisticsTable::synchronize($ownerID, array('START_DATE' => $startDate, 'END_DATE' => $endDate, 'RESPONSIBLE_ID' => $responsibleID, 'STAGE_SEMANTIC_ID' => $semanticID, 'STAGE_ID' => $stageID, 'IS_LOST' => $isLost ? 'Y' : 'N', 'TOTAL_SUM' => $sum));
     }
     return true;
 }
Exemplo n.º 14
0
    if ($arParams['arUserField']['SETTINGS']['LEAD'] == 'Y' && isset($arValue['LEAD']) && !empty($arValue['LEAD'])) {
        $dbRes = CCrmLead::GetListEx(array('TITLE' => 'ASC'), array('=ID' => $arValue['LEAD']), false, false, array('ID', 'TITLE'));
        while ($arRes = $dbRes->Fetch()) {
            $arResult['VALUE']['LEAD'][$arRes['ID']] = array('ENTITY_TITLE' => $arRes['TITLE'], 'ENTITY_LINK' => CComponentEngine::MakePathFromTemplate(COption::GetOptionString('crm', 'path_to_lead_show'), array('lead_id' => $arRes['ID'])));
        }
    }
    if ($arParams['arUserField']['SETTINGS']['CONTACT'] == 'Y' && isset($arValue['CONTACT']) && !empty($arValue['CONTACT'])) {
        $hasNameFormatter = method_exists("CCrmContact", "PrepareFormattedName");
        $dbRes = CCrmContact::GetListEx(array('LAST_NAME' => 'ASC', 'NAME' => 'ASC'), array('=ID' => $arValue['CONTACT']), false, false, $hasNameFormatter ? array('ID', 'HONORIFIC', 'NAME', 'SECOND_NAME', 'LAST_NAME') : array('ID', 'FULL_NAME'));
        while ($arRes = $dbRes->Fetch()) {
            if ($hasNameFormatter) {
                $title = CCrmContact::PrepareFormattedName(array('HONORIFIC' => isset($arRes['HONORIFIC']) ? $arRes['HONORIFIC'] : '', 'NAME' => isset($arRes['NAME']) ? $arRes['NAME'] : '', 'SECOND_NAME' => isset($arRes['SECOND_NAME']) ? $arRes['SECOND_NAME'] : '', 'LAST_NAME' => isset($arRes['LAST_NAME']) ? $arRes['LAST_NAME'] : ''));
            } else {
                $title = isset($arRes['FULL_NAME']) ? $arRes['FULL_NAME'] : '';
            }
            $arResult['VALUE']['CONTACT'][$arRes['ID']] = array('ENTITY_TITLE' => $title, 'ENTITY_LINK' => CComponentEngine::MakePathFromTemplate(COption::GetOptionString('crm', 'path_to_contact_show'), array('contact_id' => $arRes['ID'])));
        }
    }
    if ($arParams['arUserField']['SETTINGS']['COMPANY'] == 'Y' && isset($arValue['COMPANY']) && !empty($arValue['COMPANY'])) {
        $dbRes = CCrmCompany::GetListEx(array('TITLE' => 'ASC'), array('ID' => $arValue['COMPANY']));
        while ($arRes = $dbRes->Fetch()) {
            $arResult['VALUE']['COMPANY'][$arRes['ID']] = array('ENTITY_TITLE' => $arRes['TITLE'], 'ENTITY_LINK' => CComponentEngine::MakePathFromTemplate(COption::GetOptionString('crm', 'path_to_company_show'), array('company_id' => $arRes['ID'])));
        }
    }
    if ($arParams['arUserField']['SETTINGS']['DEAL'] == 'Y' && isset($arValue['DEAL']) && !empty($arValue['DEAL'])) {
        $dbRes = CCrmDeal::GetListEx(array('TITLE' => 'ASC'), array('ID' => $arValue['DEAL']));
        while ($arRes = $dbRes->Fetch()) {
            $arResult['VALUE']['DEAL'][$arRes['ID']] = array('ENTITY_TITLE' => $arRes['TITLE'], 'ENTITY_LINK' => CComponentEngine::MakePathFromTemplate(COption::GetOptionString('crm', 'path_to_deal_show'), array('deal_id' => $arRes['ID'])));
        }
    }
}
Exemplo n.º 15
0
 if (COption::GetOptionString('crm', '~CRM_REBUILD_DEAL_ATTR', 'N') !== 'Y') {
     __CrmConfigPermsEndResonse(array('STATUS' => 'NOT_REQUIRED', 'SUMMARY' => GetMessage('CRM_CONFIG_PERMS_REBUILD_ATTR_NOT_REQUIRED_SUMMARY')));
 }
 $progressData = COption::GetOptionString('crm', '~CRM_REBUILD_DEAL_ATTR_PROGRESS', '');
 $progressData = $progressData !== '' ? unserialize($progressData) : array();
 $lastItemID = isset($progressData['LAST_ITEM_ID']) ? intval($progressData['LAST_ITEM_ID']) : 0;
 $processedItemQty = isset($progressData['PROCESSED_ITEMS']) ? intval($progressData['PROCESSED_ITEMS']) : 0;
 $totalItemQty = isset($progressData['TOTAL_ITEMS']) ? intval($progressData['TOTAL_ITEMS']) : 0;
 if ($totalItemQty <= 0) {
     $totalItemQty = CCrmDeal::GetListEx(array(), array('CHECK_PERMISSIONS' => 'N'), array(), false);
 }
 $filter = array('CHECK_PERMISSIONS' => 'N');
 if ($lastItemID > 0) {
     $filter['>ID'] = $lastItemID;
 }
 $dbResult = CCrmDeal::GetListEx(array('ID' => 'ASC'), $filter, false, array('nTopCount' => 10), array('ID'));
 $itemIDs = array();
 $itemQty = 0;
 if (is_object($dbResult)) {
     while ($fields = $dbResult->Fetch()) {
         $itemIDs[] = intval($fields['ID']);
         $itemQty++;
     }
 }
 if ($itemQty > 0) {
     CCrmDeal::RebuildEntityAccessAttrs($itemIDs);
     $progressData['TOTAL_ITEMS'] = $totalItemQty;
     $processedItemQty += $itemQty;
     $progressData['PROCESSED_ITEMS'] = $processedItemQty;
     $progressData['LAST_ITEM_ID'] = $itemIDs[$itemQty - 1];
     COption::SetOptionString('crm', '~CRM_REBUILD_DEAL_ATTR_PROGRESS', serialize($progressData));
Exemplo n.º 16
0
            }
        } else {
            $fieldNames[] = $_POST['FIELD_NAME'];
            if (!$hasUserFields) {
                $hasUserFields = strncmp($_POST['FIELD_NAME'], 'UF_', 3) === 0;
            }
        }
    }
    if (count($fieldNames) == 0) {
        __CrmDealShowEndJsonResonse(array('ERROR' => 'FIELD_NAME IS NOT DEFINED!'));
    }
    $fieldValues = array();
    if (isset($_POST['FIELD_VALUE'])) {
        if (is_array($_POST['FIELD_VALUE'])) {
            $fieldValues = $_POST['FIELD_VALUE'];
        } else {
            $fieldValues[] = $_POST['FIELD_VALUE'];
        }
    }
    $dbResult = CCrmDeal::GetListEx(array(), array('=ID' => $ID, 'CHECK_PERMISSIONS' => 'N'), false, false, array('*', 'UF_*'));
    $arFields = is_object($dbResult) ? $dbResult->Fetch() : null;
    if (is_array($arFields)) {
        CCrmInstantEditorHelper::PrepareUpdate(CCrmOwnerType::Deal, $arFields, $fieldNames, $fieldValues);
        $disableUserFieldCheck = !$hasUserFields && isset($_POST['DISABLE_USER_FIELD_CHECK']) && strtoupper($_POST['DISABLE_USER_FIELD_CHECK']) === 'Y';
        if ($CCrmDeal->Update($ID, $arFields, true, true, array('REGISTER_SONET_EVENT' => true, 'DISABLE_USER_FIELD_CHECK' => $disableUserFieldCheck))) {
            $arErrors = array();
            CCrmBizProcHelper::AutoStartWorkflows(CCrmOwnerType::Deal, $ID, CCrmBizProcEventType::Edit, $arErrors);
        }
    }
}
die;
Exemplo n.º 17
0
             }
         }
     }
     break;
 case 'CONTACT':
     $CCrmContact = new CCrmContact();
     $CCrmContact->Update($_POST['ENTITY_ID'], $arField = array(), false);
     break;
 case 'COMPANY':
     $CCrmCompany = new CCrmCompany();
     $CCrmCompany->Update($_POST['ENTITY_ID'], $arField = array(), false);
     break;
 case 'DEAL':
     if (isset($_POST['STAGE_ID'])) {
         $stageID = $_POST['STAGE_ID'];
         $dbResult = CCrmDeal::GetListEx(array(), array('=ID' => $entityID), false, false, array('STAGE_ID'));
         $arPrevious = $dbResult ? $dbResult->Fetch() : null;
         if (is_array($arPrevious) && isset($arPrevious['STAGE_ID']) && $arPrevious['STAGE_ID'] !== $stageID) {
             $CCrmDeal = new CCrmDeal();
             $arField = array('STAGE_ID' => $stageID);
             if ($CCrmDeal->Update($entityID, $arField)) {
                 $arErrors = array();
                 CCrmBizProcHelper::AutoStartWorkflows(CCrmOwnerType::Deal, $entityID, CCrmBizProcEventType::Edit, $arErrors);
             }
         }
     }
     break;
 case 'QUOTE':
     if (isset($_POST['STATUS_ID'])) {
         $statusID = $_POST['STATUS_ID'];
         $dbResult = CCrmQuote::GetList(array(), array('=ID' => $entityID), false, false, array('STATUS_ID'));
Exemplo n.º 18
0
 public static function findByPhoneNumber($number, $params = array())
 {
     if (!is_string($number)) {
         throw new \Bitrix\Main\ArgumentTypeException('number', 'string');
     }
     if ($number === '') {
         throw new \Bitrix\Main\ArgumentException('Is empty', 'number');
     }
     if (!is_array($params)) {
         $params = array();
     }
     $userID = isset($params['USER_ID']) ? intval($params['USER_ID']) : 0;
     if ($userID <= 0) {
         $userID = CCrmPerms::GetCurrentUserID();
     }
     $isAdmin = CCrmPerms::IsAdmin($userID);
     $userPermissions = CCrmPerms::GetUserPermissions($userID);
     $enableExtendedMode = isset($params['ENABLE_EXTENDED_MODE']) ? (bool) $params['ENABLE_EXTENDED_MODE'] : true;
     $contactFormID = isset($params['CONTACT_FORM_ID']) ? intval($params['CONTACT_FORM_ID']) : '';
     if ($contactFormID === '') {
         $contactFormID = CCrmContact::DEFAULT_FORM_ID;
     }
     $dups = array();
     $criterion = new \Bitrix\Crm\Integrity\DuplicateCommunicationCriterion('PHONE', $number);
     $entityTypes = array(CCrmOwnerType::Contact, CCrmOwnerType::Company, CCrmOwnerType::Lead);
     foreach ($entityTypes as $entityType) {
         $duplicate = $criterion->find($entityType, 1);
         if ($duplicate !== null) {
             $dups[] = $duplicate;
         }
     }
     $entityByType = array();
     foreach ($dups as &$dup) {
         /** @var \Bitrix\Crm\Integrity\Duplicate $dup */
         $entities = $dup->getEntities();
         if (!(is_array($entities) && !empty($entities))) {
             continue;
         }
         //Each entity type limited by 50 items
         foreach ($entities as &$entity) {
             /** @var \Bitrix\Crm\Integrity\DuplicateEntity $entity */
             $entityTypeID = $entity->getEntityTypeID();
             $entityID = $entity->getEntityID();
             $fields = null;
             if ($entityTypeID === CCrmOwnerType::Contact) {
                 $dbEntity = CCrmContact::GetListEx(array(), array('=ID' => $entityID, 'CHECK_PERMISSIONS' => 'N'), false, false, array('ID', 'HONORIFIC', 'NAME', 'SECOND_NAME', 'LAST_NAME', 'PHOTO', 'POST', 'COMPANY_ID', 'COMPANY_TITLE', 'ASSIGNED_BY_ID'));
                 $entityFields = is_object($dbEntity) ? $dbEntity->Fetch() : null;
                 if (is_array($entityFields)) {
                     $formattedName = CCrmContact::PrepareFormattedName(array('HONORIFIC' => isset($entityFields['HONORIFIC']) ? $entityFields['HONORIFIC'] : '', 'NAME' => isset($entityFields['NAME']) ? $entityFields['NAME'] : '', 'SECOND_NAME' => isset($entityFields['SECOND_NAME']) ? $entityFields['SECOND_NAME'] : '', 'LAST_NAME' => isset($entityFields['LAST_NAME']) ? $entityFields['LAST_NAME'] : ''));
                     $fields = array('ID' => intval($entityFields['ID']), 'FORMATTED_NAME' => $formattedName, 'PHOTO' => isset($entityFields['PHOTO']) ? intval($entityFields['PHOTO']) : 0, 'COMPANY_ID' => isset($entityFields['COMPANY_ID']) ? intval($entityFields['COMPANY_ID']) : 0, 'COMPANY_TITLE' => isset($entityFields['COMPANY_TITLE']) ? $entityFields['COMPANY_TITLE'] : '', 'POST' => isset($entityFields['POST']) ? $entityFields['POST'] : '', 'ASSIGNED_BY_ID' => isset($entityFields['ASSIGNED_BY_ID']) ? intval($entityFields['ASSIGNED_BY_ID']) : 0, 'CAN_READ' => CCrmContact::CheckReadPermission($entityID, $userPermissions));
                     if ($fields['CAN_READ'] && $enableExtendedMode) {
                         $deals = array();
                         $dbDeal = CCrmDeal::GetListEx(array('BEGINDATE' => 'ASC'), array('=CONTACT_ID' => $entityID, 'CLOSED' => 'N', 'CHECK_PERMISSIONS' => $isAdmin ? 'N' : 'Y'), false, array('nTopCount' => 2), array('ID', 'TITLE', 'STAGE_ID'), array('PERMS' => $userPermissions));
                         if (is_object($dbDeal)) {
                             while ($dealFields = $dbDeal->Fetch()) {
                                 $dealID = intval($dealFields['ID']);
                                 //$dealFields['CAN_READ'] = CCrmDeal::CheckReadPermission($dealID, $userPermissions);
                                 $dealFields['SHOW_URL'] = CCrmOwnerType::GetShowUrl(CCrmOwnerType::Deal, $dealID);
                                 $deals[] = $dealFields;
                             }
                         }
                         $fields['DEALS'] =& $deals;
                         unset($deals);
                     }
                 }
             } elseif ($entityTypeID === CCrmOwnerType::Company) {
                 $dbEntity = CCrmCompany::GetListEx(array(), array('=ID' => $entityID, 'CHECK_PERMISSIONS' => 'N'), false, false, array('ID', 'TITLE', 'LOGO', 'ASSIGNED_BY_ID'));
                 $entityFields = is_object($dbEntity) ? $dbEntity->Fetch() : null;
                 if (is_array($entityFields)) {
                     $fields = array('ID' => intval($entityFields['ID']), 'TITLE' => isset($entityFields['TITLE']) ? $entityFields['TITLE'] : '', 'LOGO' => isset($entityFields['LOGO']) ? intval($entityFields['LOGO']) : 0, 'ASSIGNED_BY_ID' => isset($entityFields['ASSIGNED_BY_ID']) ? intval($entityFields['ASSIGNED_BY_ID']) : 0, 'CAN_READ' => CCrmCompany::CheckReadPermission($entityID, $userPermissions));
                     if ($fields['CAN_READ'] && $enableExtendedMode) {
                         $deals = array();
                         $dbDeal = CCrmDeal::GetListEx(array('BEGINDATE' => 'ASC'), array('=COMPANY_ID' => $entityID, 'CLOSED' => 'N', 'CHECK_PERMISSIONS' => $isAdmin ? 'N' : 'Y'), false, array('nTopCount' => 2), array('ID', 'TITLE', 'STAGE_ID'), array('PERMS' => $userPermissions));
                         if (is_object($dbDeal)) {
                             while ($dealFields = $dbDeal->Fetch()) {
                                 $dealID = intval($dealFields['ID']);
                                 //$dealFields['CAN_READ'] = CCrmDeal::CheckReadPermission($dealID, $userPermissions);
                                 $dealFields['SHOW_URL'] = CCrmOwnerType::GetShowUrl(CCrmOwnerType::Deal, $dealID);
                                 $deals[] = $dealFields;
                             }
                         }
                         $fields['DEALS'] =& $deals;
                         unset($deals);
                     }
                 }
             } elseif ($entityTypeID === CCrmOwnerType::Lead) {
                 $dbEntity = CCrmLead::GetListEx(array(), array('=ID' => $entityID, 'CHECK_PERMISSIONS' => 'N'), false, false, array('ID', 'TITLE', 'HONORIFIC', 'NAME', 'SECOND_NAME', 'LAST_NAME', 'POST', 'COMPANY_TITLE', 'ASSIGNED_BY_ID'));
                 $entityFields = is_object($dbEntity) ? $dbEntity->Fetch() : null;
                 if (is_array($entityFields)) {
                     $formattedName = '';
                     if (!empty($entityFields['NAME']) || !empty($entityFields['SECOND_NAME']) || !empty($entityFields['LAST_NAME'])) {
                         $formattedName = CCrmLead::PrepareFormattedName(array('HONORIFIC' => isset($entityFields['HONORIFIC']) ? $entityFields['HONORIFIC'] : '', 'NAME' => isset($entityFields['NAME']) ? $entityFields['NAME'] : '', 'SECOND_NAME' => isset($entityFields['SECOND_NAME']) ? $entityFields['SECOND_NAME'] : '', 'LAST_NAME' => isset($entityFields['LAST_NAME']) ? $entityFields['LAST_NAME'] : ''));
                     }
                     $fields = array('ID' => intval($entityFields['ID']), 'TITLE' => isset($entityFields['TITLE']) ? $entityFields['TITLE'] : '', 'FORMATTED_NAME' => $formattedName, 'COMPANY_TITLE' => isset($entityFields['COMPANY_TITLE']) ? $entityFields['COMPANY_TITLE'] : '', 'POST' => isset($entityFields['POST']) ? $entityFields['POST'] : '', 'ASSIGNED_BY_ID' => isset($entityFields['ASSIGNED_BY_ID']) ? intval($entityFields['ASSIGNED_BY_ID']) : 0, 'CAN_READ' => CCrmLead::CheckReadPermission($entityID, $userPermissions));
                 }
             }
             if (!is_array($fields)) {
                 continue;
             }
             if ($fields['CAN_READ'] && $enableExtendedMode) {
                 $showUrl = $fields['SHOW_URL'] = CCrmOwnerType::GetShowUrl($entityTypeID, $entityID);
                 if ($showUrl !== '') {
                     $fields['ACTIVITY_LIST_URL'] = CCrmUrlUtil::AddUrlParams($showUrl, array("{$contactFormID}_active_tab" => 'tab_activity'));
                     $fields['INVOICE_LIST_URL'] = CCrmUrlUtil::AddUrlParams($showUrl, array("{$contactFormID}_active_tab" => 'tab_invoice'));
                     if ($entityTypeID === CCrmOwnerType::Contact || $entityTypeID === CCrmOwnerType::Company) {
                         $fields['DEAL_LIST_URL'] = CCrmUrlUtil::AddUrlParams($showUrl, array("{$contactFormID}_active_tab" => 'tab_deal'));
                     }
                 }
                 $activities = array();
                 $dbActivity = CCrmActivity::GetList(array('DEADLINE' => 'ASC'), array('COMPLETED' => 'N', 'BINDINGS' => array(array('OWNER_TYPE_ID' => $entityTypeID, 'OWNER_ID' => $entityID)), 'CHECK_PERMISSIONS' => $isAdmin ? 'N' : 'Y'), false, array('nTopCount' => 4), array('ID', 'SUBJECT', 'START_TIME', 'END_TIME', 'DEADLINE'), array('PERMS' => $userPermissions));
                 if (is_object($dbActivity)) {
                     while ($activityFields = $dbActivity->Fetch()) {
                         $activityFields['SHOW_URL'] = CCrmOwnerType::GetShowUrl(CCrmOwnerType::Activity, $activityFields['ID']);
                         $activities[] =& $activityFields;
                         unset($activityFields);
                     }
                 }
                 $fields['ACTIVITIES'] =& $activities;
                 unset($activities);
             }
             $entityTypeName = CCrmOwnerType::ResolveName($entityTypeID);
             if (!isset($entityByType[$entityTypeName])) {
                 $entityByType[$entityTypeName] = array($fields);
             } elseif (!in_array($entityID, $entityByType[$entityTypeName], true)) {
                 $entityByType[$entityTypeName][] = $fields;
             }
         }
     }
     unset($dup);
     return $entityByType;
 }
Exemplo n.º 19
0
 public static function TryGetInfo($typeID, $ID, &$info, $bCheckPermissions = false)
 {
     $typeID = intval($typeID);
     $ID = intval($ID);
     if ($ID <= 0) {
         return array();
     }
     $result = null;
     switch ($typeID) {
         case self::Lead:
             $dbRes = CCrmLead::GetListEx(array(), array('=ID' => $ID, 'CHECK_PERMISSIONS' => $bCheckPermissions ? 'Y' : 'N'), false, false, array('TITLE'));
             $arRes = $dbRes ? $dbRes->Fetch() : null;
             if (is_array($arRes)) {
                 $info = array('CAPTION' => isset($arRes['TITLE']) ? $arRes['TITLE'] : '', 'IMAGE_ID' => 0);
                 return true;
             }
             break;
         case self::Contact:
             $dbRes = CCrmContact::GetListEx(array(), array('=ID' => $ID, 'CHECK_PERMISSIONS' => $bCheckPermissions ? 'Y' : 'N'), false, false, array('NAME', 'SECOND_NAME', 'LAST_NAME', 'PHOTO'));
             $arRes = $dbRes ? $dbRes->Fetch() : null;
             if (is_array($arRes)) {
                 $info = array('CAPTION' => CUser::FormatName(\Bitrix\Crm\Format\PersonNameFormatter::getFormat(), array('LOGIN' => '', 'NAME' => isset($arRes['NAME']) ? $arRes['NAME'] : '', 'SECOND_NAME' => isset($arRes['SECOND_NAME']) ? $arRes['SECOND_NAME'] : '', 'LAST_NAME' => isset($arRes['LAST_NAME']) ? $arRes['LAST_NAME'] : ''), false, false), 'IMAGE_ID' => isset($arRes['PHOTO']) ? intval($arRes['PHOTO']) : 0);
                 return true;
             }
             break;
         case self::Company:
             $dbRes = CCrmCompany::GetListEx(array(), array('=ID' => $ID, 'CHECK_PERMISSIONS' => $bCheckPermissions ? 'Y' : 'N'), false, false, array('TITLE', 'LOGO'));
             $arRes = $dbRes ? $dbRes->Fetch() : null;
             if (is_array($arRes)) {
                 $info = array('CAPTION' => isset($arRes['TITLE']) ? $arRes['TITLE'] : '', 'IMAGE_ID' => isset($arRes['LOGO']) ? intval($arRes['LOGO']) : 0);
                 return true;
             }
             break;
         case self::Deal:
             $dbRes = CCrmDeal::GetListEx(array(), array('=ID' => $ID, 'CHECK_PERMISSIONS' => $bCheckPermissions ? 'Y' : 'N'), false, false, array('TITLE'));
             $arRes = $dbRes ? $dbRes->Fetch() : null;
             if (is_array($arRes)) {
                 $info = array('CAPTION' => isset($arRes['TITLE']) ? $arRes['TITLE'] : '', 'IMAGE_ID' => 0);
                 return true;
             }
             break;
         case self::Invoice:
             $dbRes = CCrmInvoice::GetList(array(), array('ID' => $ID), false, false, array('ORDER_TOPIC'));
             $arRes = $dbRes ? $dbRes->Fetch() : null;
             if (is_array($arRes)) {
                 $info = array('CAPTION' => isset($arRes['ORDER_TOPIC']) ? $arRes['ORDER_TOPIC'] : '', 'IMAGE_ID' => 0);
                 return true;
             }
             break;
         case self::Quote:
             $dbRes = CCrmQuote::GetList(array(), array('=ID' => $ID, 'CHECK_PERMISSIONS' => $bCheckPermissions ? 'Y' : 'N'), false, false, array('TITLE'));
             $arRes = $dbRes ? $dbRes->Fetch() : null;
             if (is_array($arRes)) {
                 $info = array('CAPTION' => isset($arRes['TITLE']) ? $arRes['TITLE'] : '', 'IMAGE_ID' => 0);
                 return true;
             }
             break;
     }
     return false;
 }
Exemplo n.º 20
0
     $gridFilter = $gridOptions->GetFilter(array());
     //Clear service fields
     if (isset($gridFilter['GRID_FILTER_APPLIED'])) {
         unset($gridFilter['GRID_FILTER_APPLIED']);
     }
     if (isset($gridFilter['GRID_FILTER_ID'])) {
         unset($gridFilter['GRID_FILTER_ID']);
     }
     if (is_array($gridFilter) && !empty($gridFilter)) {
         $dbEntities = null;
         if ($entityType === 'LEAD') {
             CCrmLead::PrepareFilter($gridFilter);
             $dbEntities = CCrmLead::GetListEx(array(), $gridFilter, false, false, array('ID'));
         } elseif ($entityType === 'DEAL') {
             CCrmDeal::PrepareFilter($gridFilter);
             $dbEntities = CCrmDeal::GetListEx(array(), $gridFilter, false, false, array('ID'));
         } elseif ($entityType === 'COMPANY') {
             CCrmCompany::PrepareFilter($gridFilter);
             $dbEntities = CCrmCompany::GetListEx(array(), $gridFilter, false, false, array('ID'));
         } elseif ($entityType === 'CONTACT') {
             CCrmContact::PrepareFilter($gridFilter);
             $dbEntities = CCrmContact::GetListEx(array(), $gridFilter, false, false, array('ID'));
         }
         if ($dbEntities) {
             while ($arEntity = $dbEntities->Fetch()) {
                 $arEntityID[] = $arEntity['ID'];
             }
         }
     }
 }
 $arFilter = array('ENTITY_ID' => $entityType, 'TYPE_ID' => $communicationType, '@VALUE_TYPE' => array('WORK', 'HOME', 'OTHER'));
Exemplo n.º 21
0
 public static function GetUsersFromUserGroup($group, $documentId)
 {
     $groupLc = strtolower($group);
     if ($groupLc == 'author') {
         $arDocumentID = self::GetDocumentInfo($documentId);
         if (empty($arDocumentID)) {
             return array();
         }
         $dbDocumentList = null;
         $entityID = isset($arDocumentID['ID']) ? intval($arDocumentID['ID']) : 0;
         if ($entityID > 0) {
             switch ($arDocumentID['TYPE']) {
                 case 'CONTACT':
                     $dbDocumentList = CCrmContact::GetListEx(array(), array('ID' => $entityID, 'CHECK_PERMISSIONS' => 'N'), false, false, array('ASSIGNED_BY_ID'));
                     break;
                 case 'COMPANY':
                     $dbDocumentList = CCrmCompany::GetListEx(array(), array('ID' => $entityID, 'CHECK_PERMISSIONS' => 'N'), false, false, array('ASSIGNED_BY_ID'));
                     break;
                 case 'DEAL':
                     $dbDocumentList = CCrmDeal::GetListEx(array(), array('ID' => $entityID, 'CHECK_PERMISSIONS' => 'N'), false, false, array('ASSIGNED_BY_ID'));
                     break;
                 case 'LEAD':
                     $dbDocumentList = CCrmLead::GetListEx(array(), array('ID' => $entityID, 'CHECK_PERMISSIONS' => 'N'), false, false, array('ASSIGNED_BY_ID'));
                     break;
             }
         }
         $arFields = is_object($dbDocumentList) ? $dbDocumentList->Fetch() : null;
         return is_array($arFields) && isset($arFields['ASSIGNED_BY_ID']) ? array($arFields['ASSIGNED_BY_ID']) : array();
     } elseif ($groupLc == 'ungrouped') {
         return isset(self::$UNGROUPED_USERS[$documentId]) ? self::$UNGROUPED_USERS[$documentId] : array();
     }
     $group = (int) $group;
     if ($group <= 0) {
         return array();
     }
     $arResult = array();
     $dbUsersList = CUser::GetList($b = 'ID', $o = 'ASC', array('GROUPS_ID' => $group, 'ACTIVE' => 'Y'));
     while ($arUser = $dbUsersList->Fetch()) {
         $arResult[] = $arUser['ID'];
     }
     return $arResult;
 }
Exemplo n.º 22
0
}
if ($entityTypeName && $entityID) {
    if (isset($types[$entityTypeName])) {
        if (empty($arResult['ENTITY_DATA'])) {
            $arResult['FEED_DESTINATION']['SELECTED']['CRM' . $entityTypeName . $entityID] = $types[$entityTypeName];
        }
        if (!isset($arResult['FEED_DESTINATION'][strtoupper($types[$entityTypeName])]['CRM' . $entityTypeName . $entityID])) {
            switch ($entityTypeName) {
                case 'CONTACT':
                    $dbEntity = CCrmContact::GetListEx(array(), array('ID' => $entityID), false, array(), array('ID', 'NAME', 'SECOND_NAME', 'LAST_NAME', 'COMPANY_TITLE', 'PHOTO'));
                    break;
                case 'COMPANY':
                    $dbEntity = CCrmCompany::GetListEx(array(), array('ID' => $entityID), false, array(), array('ID', 'TITLE', 'COMPANY_TYPE', 'INDUSTRY', 'LOGO'));
                    break;
                case 'LEAD':
                    $dbEntity = CCrmLead::GetListEx(array(), array('ID' => $entityID), false, array(), array('ID', 'TITLE', 'NAME', 'SECOND_NAME', 'LAST_NAME', 'STATUS_ID'));
                    break;
                case 'DEAL':
                    $dbEntity = CCrmDeal::GetListEx(array(), array('ID' => $entityID), false, array(), array('ID', 'TITLE', 'STAGE_ID'));
                    break;
                default:
                    $dbEntity = null;
            }
            if ($dbEntity && ($arEntity = $dbEntity->fetch())) {
                $arResult['FEED_DESTINATION'][strtoupper($types[$entityTypeName])]['CRM' . $entityTypeName . $arEntity['ID']] = prepareCrmEntity(strtolower($entityTypeName), $arEntity);
            }
        }
    }
}
$arResult['FEED_DESTINATION']['DENY_TOALL'] = !$allowLiveFeedToAll;
$this->IncludeComponentTemplate();
 /**
  * @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;
 }
Exemplo n.º 24
0
							$siteNameFormat,
							array(
								'LOGIN'       => '',
								'NAME'        => $arLead['NAME'],
								'SECOND_NAME' => $arLead['SECOND_NAME'],
								'LAST_NAME'   => $arLead['LAST_NAME']
							),
							false, false
						))
					);
				}

				$dbDeals = CCrmDeal::GetListEx(
					$arOrder = array(),
					$arFilter = array('%TITLE' => $search),
					$arGroupBy = false,
					$arNavStartParams = array('nTopCount' => 20),
					$arSelectFields = array('ID', 'TITLE', 'COMPANY_TITLE', 'CONTACT_NAME', 'CONTACT_SECOND_NAME', 'CONTACT_LAST_NAME')
				);
				$arDeals = array();
				while ($dbDeals && ($arDeal = $dbDeals->fetch()))
				{
					$arDesc = array();
					if ($arDeal['COMPANY_TITLE'] != '')
						$arDesc[] = $arDeal['COMPANY_TITLE'];
					$arDesc[] = CUser::FormatName(
						$siteNameFormat,
						array(
							'LOGIN'       => '',
							'NAME'        => $arDeal['CONTACT_NAME'],
							'SECOND_NAME' => $arDeal['CONTACT_SECOND_NAME'],
Exemplo n.º 25
0
 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;
 }
Exemplo n.º 26
0
if (!$isPermitted) {
    ShowError(GetMessage('CRM_PERMISSION_DENIED'));
    return;
}
$arEntityAttr = $arParams['ELEMENT_ID'] > 0 ? $userPermissions->GetEntityAttr('DEAL', array($arParams['ELEMENT_ID'])) : array();
$bInternal = false;
if (isset($arParams['INTERNAL_FILTER']) && !empty($arParams['INTERNAL_FILTER'])) {
    $bInternal = true;
}
$arResult['INTERNAL'] = $bInternal;
$bTaxMode = CCrmTax::isTaxMode();
$arResult['TAX_MODE'] = $bTaxMode ? 'Y' : 'N';
$arFields = null;
if ($bEdit || $bCopy) {
    $arFilter = array('ID' => $arParams['ELEMENT_ID'], 'PERMISSION' => 'WRITE');
    $obFields = CCrmDeal::GetListEx(array(), $arFilter);
    $arFields = $obFields->GetNext();
    if ($arFields === false) {
        $bEdit = false;
        $bCopy = false;
    }
    if ($bCopy) {
        if (isset($arFields['LEAD_ID'])) {
            unset($arFields['LEAD_ID']);
        }
        if (isset($arFields['~LEAD_ID'])) {
            unset($arFields['~LEAD_ID']);
        }
        $res = CCrmFieldMulti::GetList(array('ID' => 'asc'), array('ENTITY_ID' => 'DEAL', 'ELEMENT_ID' => $arParams['ELEMENT_ID']));
        $arResult['ELEMENT']['FM'] = array();
        while ($ar = $res->Fetch()) {
Exemplo n.º 27
0
                 continue;
             }
             $productID = isset($arProduct['ID']) ? $arProduct['ID'] : 0;
             if ($productID <= 0) {
                 continue;
             }
             $arProductRows = array(array('PRODUCT_ID' => $productID, 'PRICE' => isset($arLead['OPPORTUNITY']) ? doubleval($arLead['OPPORTUNITY']) : 0.0, 'QUANTITY' => 1));
             CCrmLead::SaveProductRows($ID, $arProductRows);
         }
     }
     COption::SetOptionString('crm', '~crm_11_0_6_convertion', 'Y');
 }
 // <-- Convert LEAD CURRENCY and PRODUCT
 // Convert DEAL EVENTS -->
 if (COption::GetOptionString('crm', '~CRM_DEAL_EVENT_CONVERT_11_5_7', 'N') !== 'Y') {
     $dbDeals = CCrmDeal::GetListEx(array(), array('@EVENT_ID' => array('PHONE', 'INFO')), false, false, array());
     while ($arDeal = $dbDeals->Fetch()) {
         CCrmActivity::CreateFromDealEvent($arDeal);
     }
     COption::SetOptionString('crm', '~CRM_DEAL_EVENT_CONVERT_11_5_7', 'Y');
 }
 // <-- Convert DEAL EVENTS
 // SETUP DEFAULT RESPONSIBLE FOR COMPANIES-->
 if (COption::GetOptionString('crm', '~CRM_COMPANY_RESPONSIBLE_11_5_7', 'N') !== 'Y') {
     try {
         if (CCrmCompany::SetDefaultResponsible(true)) {
             COption::SetOptionString('crm', '~CRM_COMPANY_RESPONSIBLE_11_5_7', 'Y');
         }
     } catch (Exception $e) {
     }
 }
Exemplo n.º 28
0
$arResult['STAGE_LIST'] = CCrmStatus::GetStatusList('DEAL_STAGE');
$arResult['TYPE_LIST'] = CCrmStatus::GetStatusList('DEAL_TYPE');
$arResult['CURRENCY_LIST'] = CCrmCurrencyHelper::PrepareListItems();
$serviceURLTemplate = $arParams["SERVICE_URL_TEMPLATE"] ? $arParams["SERVICE_URL_TEMPLATE"] : '#SITE_DIR#bitrix/components/bitrix/mobile.crm.deal.edit/ajax.php?site_id=#SITE#&sessid=#SID#';
$arResult['SERVICE_URL'] = CComponentEngine::makePathFromTemplate($serviceURLTemplate, array('SID' => bitrix_sessid()));
// CONTEXT_ID -->
$contextID = isset($arParams['CONTEXT_ID']) ? $arParams['CONTEXT_ID'] : '';
if ($contextID === '' && isset($_REQUEST['context_id'])) {
    $contextID = $_REQUEST['context_id'];
}
if ($contextID === '') {
    $contextID = "{$uid}_{$entityID}";
}
$arResult['CONTEXT_ID'] = $arParams['CONTEXT_ID'] = $contextID;
//<-- CONTEXT_ID
$dbFields = CCrmDeal::GetListEx(array(), array('ID' => $entityID));
$arFields = $dbFields->GetNext();
if (!$arFields) {
    ShowError(GetMessage('CRM_DEAL_VIEW_NOT_FOUND', array('#ID#' => $arParams['ENTITY_ID'])));
    return;
}
$arResult['PERMISSIONS'] = array('EDIT' => CCrmDeal::CheckUpdatePermission($entityID, $userPerms), 'DELETE' => CCrmDeal::CheckDeletePermission($entityID, $userPerms));
$arFields['~CONTACT_ID'] = isset($arFields['~CONTACT_ID']) ? intval($arFields['~CONTACT_ID']) : 0;
$arFields['~CONTACT_NAME'] = isset($arFields['~CONTACT_NAME']) ? $arFields['~CONTACT_NAME'] : '';
$arFields['~CONTACT_LAST_NAME'] = isset($arFields['~CONTACT_LAST_NAME']) ? $arFields['~CONTACT_LAST_NAME'] : '';
$arFields['~CONTACT_SECOND_NAME'] = isset($arFields['~CONTACT_SECOND_NAME']) ? $arFields['~CONTACT_SECOND_NAME'] : '';
$arFields['~CONTACT_POST'] = isset($arFields['~CONTACT_POST']) ? $arFields['~CONTACT_POST'] : '';
$arFields['~CONTACT_PHOTO'] = isset($arFields['~CONTACT_PHOTO']) ? intval($arFields['~CONTACT_PHOTO']) : 0;
$arFields['~COMPANY_ID'] = isset($arFields['~COMPANY_ID']) ? intval($arFields['~COMPANY_ID']) : 0;
$arFields['~COMPANY_TITLE'] = isset($arFields['~COMPANY_TITLE']) ? $arFields['~COMPANY_TITLE'] : '';
$arFields['~COMPANY_LOGO'] = isset($arFields['~COMPANY_LOGO']) ? intval($arFields['~COMPANY_LOGO']) : 0;
Exemplo n.º 29
0
}
$entityTypeName = CCrmOwnerType::ResolveName($entityTypeID);
$userPerms = CCrmPerms::GetCurrentUserPermissions();
if (!CCrmAuthorizationHelper::CheckReadPermission($entityTypeName, $entityID, $userPerms)) {
    ShowError(GetMessage('CRM_PERMISSION_DENIED'));
    return;
}
$arParams['UID'] = isset($arParams['UID']) ? $arParams['UID'] : '';
if (!isset($arParams['UID']) || $arParams['UID'] === '') {
    $arParams['UID'] = 'mobile_crm_product_row_list';
}
$arResult['UID'] = $arParams['UID'];
$arResult['ITEMS'] = array();
$arResult['TAX_MODE'] = 'NONE';
if ($entityTypeID === CCrmOwnerType::Deal) {
    $dbRes = CCrmDeal::GetListEx(array(), array('ID' => $entityID, 'CHECK_PERMISSIONS' => 'N'), false, false, array('TITLE', 'CURRENCY_ID', 'OPPORTUNITY'));
    $arOwner = $dbRes ? $dbRes->Fetch() : null;
    if ($arOwner) {
        $arResult['TITLE'] = isset($arOwner['TITLE']) ? $arOwner['TITLE'] : '';
        $arResult['CURRENCY_ID'] = isset($arOwner['CURRENCY_ID']) ? $arOwner['CURRENCY_ID'] : CCrmCurrency::GetBaseCurrencyID();
        $arResult['SUM'] = isset($arOwner['OPPORTUNITY']) ? $arOwner['OPPORTUNITY'] : 0.0;
    } else {
        $arResult['TITLE'] = '';
        $arResult['CURRENCY_ID'] = CCrmCurrency::GetBaseCurrencyID();
        $arResult['SUM'] = 0.0;
    }
    $productRows = CCrmProductRow::LoadRows(CCrmOwnerTypeAbbr::Deal, $entityID);
    foreach ($productRows as &$productRow) {
        $productRow['FORMATTED_PRICE'] = CCrmCurrency::MoneyToString($productRow['PRICE'], $arResult['CURRENCY_ID']);
        $arResult['ITEMS'][] = $productRow;
    }
Exemplo n.º 30
0
 protected function innerGetList($order, $filter, $select, $navigation, &$errors)
 {
     if (!CCrmDeal::CheckReadPermission(0)) {
         $errors[] = 'Access denied.';
         return false;
     }
     $options = array('IS_EXTERNAL_CONTEXT' => true);
     if (is_array($order)) {
         if (isset($order['STAGE_ID'])) {
             $order['STAGE_SORT'] = $order['STAGE_ID'];
             unset($order['STAGE_ID']);
             $options['FIELD_OPTIONS'] = array('ADDITIONAL_FIELDS' => array('STAGE_SORT'));
         }
     }
     return CCrmDeal::GetListEx($order, $filter, false, $navigation, $select, $options);
 }