Esempio n. 1
0
 public static function Update($ID, $arFields, $checkPerms = true, $regEvent = true, $options = array())
 {
     global $DB;
     if (!is_array($options)) {
         $options = array();
     }
     $arPrevEntity = self::GetByID($ID, $checkPerms);
     if (!$arPrevEntity) {
         return false;
         // is not exists
     }
     if (!self::CheckFields('UPDATE', $arFields, $ID, array('PREVIOUS_FIELDS' => $arPrevEntity))) {
         return false;
     }
     $arPrevBindings = self::GetBindings($ID);
     $arRecordBindings = array();
     $storageElementIDs = isset($arFields['STORAGE_ELEMENT_IDS']) ? $arFields['STORAGE_ELEMENT_IDS'] : null;
     $storageElementsSerialized = false;
     if (is_array($storageElementIDs)) {
         $storageElementIDs = self::NormalizeStorageElementIDs($storageElementIDs);
         $arFields['STORAGE_ELEMENT_IDS'] = serialize($storageElementIDs);
         $storageElementsSerialized = true;
     } elseif ($storageElementIDs !== null) {
         //Skip Storage Elements Processing - Treat As Not Changed
         $storageElementIDs = null;
     }
     if (isset($arFields['STORAGE_ELEMENT_IDS'])) {
         $arRecordBindings['STORAGE_ELEMENT_IDS'] = $arFields['STORAGE_ELEMENT_IDS'];
     }
     if (isset($arFields['SETTINGS'])) {
         if (is_array($arFields['SETTINGS'])) {
             $arFields['SETTINGS'] = serialize($arFields['SETTINGS']);
         }
         $arRecordBindings['SETTINGS'] = $arFields['SETTINGS'];
     }
     if (isset($arFields['DESCRIPTION'])) {
         $arRecordBindings['DESCRIPTION'] = $arFields['DESCRIPTION'];
     }
     $arBindings = isset($arFields['BINDINGS']) && is_array($arFields['BINDINGS']) ? $arFields['BINDINGS'] : null;
     if (is_array($arBindings)) {
         $bindingQty = count($arBindings);
         if ($bindingQty === 1) {
             // Change activity ownership if only one binding defined
             $arBinding = $arBindings[0];
             $arFields['OWNER_ID'] = $arBinding['OWNER_ID'];
             $arFields['OWNER_TYPE_ID'] = $arBinding['OWNER_TYPE_ID'];
         } elseif ($bindingQty === 0) {
             // Clear activity ownership if only no bindings are defined
             $arFields['OWNER_ID'] = 0;
             $arFields['OWNER_TYPE_ID'] = CCrmOwnerType::Undefined;
         }
     }
     self::NormalizeDateTimeFields($arFields);
     if (isset($arFields['ID'])) {
         unset($arFields['ID']);
     }
     $sql = 'UPDATE ' . CCrmActivity::TABLE_NAME . ' SET ' . $DB->PrepareUpdate(CCrmActivity::TABLE_NAME, $arFields) . ' WHERE ID = ' . $ID;
     if (!empty($arRecordBindings)) {
         $DB->QueryBind($sql, $arRecordBindings, false);
     } else {
         $DB->Query($sql, false, 'File: ' . __FILE__ . '<br>Line: ' . __LINE__);
     }
     $arFields['SETTINGS'] = isset($arFields['SETTINGS']) ? unserialize($arFields['SETTINGS']) : array();
     CCrmEntityHelper::RemoveCached(self::CACHE_NAME, $ID);
     $storageTypeID = isset($arFields['STORAGE_TYPE_ID']) ? intval($arFields['STORAGE_TYPE_ID']) : StorageType::Undefined;
     if ($storageTypeID === StorageType::Undefined) {
         $storageTypeID = isset($arPrevEntity['STORAGE_TYPE_ID']) ? intval($arPrevEntity['STORAGE_TYPE_ID']) : self::GetDefaultStorageTypeID();
     }
     if (is_array($storageElementIDs)) {
         CCrmActivity::DoSaveElementIDs($ID, $storageTypeID, $storageElementIDs);
     }
     $arCurEntity = self::GetByID($ID, false);
     if (is_array($arBindings)) {
         $bindingsChanged = !self::IsBindingsEquals($arBindings, $arPrevBindings);
         if ($bindingsChanged) {
             self::SaveBindings($ID, $arBindings, false, false);
         }
     } else {
         $arBindings = $arPrevBindings;
         $bindingsChanged = false;
     }
     $prevCompleted = isset($arPrevEntity['COMPLETED']) && $arPrevEntity['COMPLETED'] === 'Y';
     $curCompleted = isset($arCurEntity['COMPLETED']) && $arCurEntity['COMPLETED'] === 'Y';
     $prevDeadline = isset($arPrevEntity['DEADLINE']) ? $arPrevEntity['DEADLINE'] : '';
     $curDeadline = isset($arCurEntity['DEADLINE']) ? $arCurEntity['DEADLINE'] : '';
     if ($prevCompleted && $prevDeadline && ($bindingsChanged || $prevCompleted != $curCompleted || $prevDeadline !== $curDeadline)) {
         $deadline = new \Bitrix\Main\Type\DateTime($prevDeadline);
         $deadline->setTime(0, 0, 0);
         foreach ($arPrevBindings as &$arBinding) {
             $curOwnerTypeID = isset($arBinding['OWNER_TYPE_ID']) ? intval($arBinding['OWNER_TYPE_ID']) : 0;
             $curOwnerID = isset($arBinding['OWNER_ID']) ? intval($arBinding['OWNER_ID']) : 0;
             if ($curOwnerTypeID === CCrmOwnerType::Deal && $curOwnerID > 0) {
                 Bitrix\Crm\Statistics\DealActivityStatisticEntry::register($curOwnerID, null, array('DATE' => $deadline));
             }
         }
         unset($arBinding);
     }
     if ($curCompleted && $curDeadline !== '') {
         $deadline = new \Bitrix\Main\Type\DateTime($curDeadline);
         $deadline->setTime(0, 0, 0);
         foreach ($arBindings as &$arBinding) {
             $curOwnerTypeID = isset($arBinding['OWNER_TYPE_ID']) ? intval($arBinding['OWNER_TYPE_ID']) : 0;
             $curOwnerID = isset($arBinding['OWNER_ID']) ? intval($arBinding['OWNER_ID']) : 0;
             if ($curOwnerTypeID === CCrmOwnerType::Deal && $curOwnerID > 0) {
                 Bitrix\Crm\Statistics\DealActivityStatisticEntry::register($curOwnerID, null, array('DATE' => $deadline));
             }
         }
         unset($arBinding);
     }
     // Synchronize user activity -->
     $arSyncKeys = array();
     $responsibleID = isset($arFields['RESPONSIBLE_ID']) ? intval($arFields['RESPONSIBLE_ID']) : (isset($arPrevEntity['RESPONSIBLE_ID']) ? intval($arPrevEntity['RESPONSIBLE_ID']) : 0);
     foreach ($arBindings as &$arBinding) {
         if ($responsibleID > 0) {
             self::SynchronizeUserActivity($arBinding['OWNER_TYPE_ID'], $arBinding['OWNER_ID'], $responsibleID);
             $arSyncKeys[] = "{$arBinding['OWNER_TYPE_ID']}_{$arBinding['OWNER_ID']}_{$responsibleID}";
         }
         self::SynchronizeUserActivity($arBinding['OWNER_TYPE_ID'], $arBinding['OWNER_ID'], 0);
         $arSyncKeys[] = "{$arBinding['OWNER_TYPE_ID']}_{$arBinding['OWNER_ID']}";
     }
     unset($arBinding);
     $prevResponsibleID = isset($arPrevEntity['RESPONSIBLE_ID']) ? intval($arPrevEntity['RESPONSIBLE_ID']) : 0;
     if (!empty($arPrevBindings)) {
         foreach ($arPrevBindings as &$arBinding) {
             if ($prevResponsibleID > 0 && !in_array("{$arBinding['OWNER_TYPE_ID']}_{$arBinding['OWNER_ID']}_{$prevResponsibleID}", $arSyncKeys, true)) {
                 self::SynchronizeUserActivity($arBinding['OWNER_TYPE_ID'], $arBinding['OWNER_ID'], $prevResponsibleID);
             }
             if (!in_array("{$arBinding['OWNER_TYPE_ID']}_{$arBinding['OWNER_ID']}", $arSyncKeys, true)) {
                 self::SynchronizeUserActivity($arBinding['OWNER_TYPE_ID'], $arBinding['OWNER_ID'], 0);
             }
         }
         unset($arBinding);
     }
     // <-- Synchronize user activity
     if ($regEvent) {
         foreach ($arBindings as &$arBinding) {
             self::RegisterUpdateEvent($arBinding['OWNER_TYPE_ID'], $arBinding['OWNER_ID'], $arCurEntity, $arPrevEntity, false);
         }
         unset($arBinding);
     }
     $typeID = isset($arCurEntity['TYPE_ID']) ? intval($arCurEntity['TYPE_ID']) : CCrmActivityType::Undefined;
     $skipAssocEntity = isset($options['SKIP_ASSOCIATED_ENTITY']) ? (bool) $options['SKIP_ASSOCIATED_ENTITY'] : false;
     if (!$skipAssocEntity && $typeID > 0) {
         switch ($typeID) {
             case CCrmActivityType::Call:
             case CCrmActivityType::Meeting:
                 $completed = isset($arCurEntity['COMPLETED']) ? $arCurEntity['COMPLETED'] === 'Y' : false;
                 // Check for settings
                 $displayCompleted = $typeID === CCrmActivityType::Call ? CCrmActivityCalendarSettings::GetValue(CCrmActivityCalendarSettings::DisplayCompletedCalls, true) : CCrmActivityCalendarSettings::GetValue(CCrmActivityCalendarSettings::DisplayCompletedMeetings, true);
                 if (!$completed || $displayCompleted) {
                     $arCurEntity['BINDINGS'] = $arBindings;
                     $eventID = self::SaveCalendarEvent($arCurEntity);
                     if (is_int($eventID) && $eventID > 0) {
                         $DB->Query('UPDATE ' . CCrmActivity::TABLE_NAME . ' SET ' . $DB->PrepareUpdate(CCrmActivity::TABLE_NAME, array('ASSOCIATED_ENTITY_ID' => $eventID)) . ' WHERE ID = ' . $ID, false, 'File: ' . __FILE__ . '<br>Line: ' . __LINE__);
                     }
                 } else {
                     if (self::DeleteCalendarEvent($arCurEntity)) {
                         $DB->Query('UPDATE ' . CCrmActivity::TABLE_NAME . ' SET ' . $DB->PrepareUpdate(CCrmActivity::TABLE_NAME, array('ASSOCIATED_ENTITY_ID' => 0)) . ' WHERE ID = ' . $ID, false, 'File: ' . __FILE__ . '<br>Line: ' . __LINE__);
                     }
                 }
                 break;
             case CCrmActivityType::Task:
                 self::SaveTask($arCurEntity);
                 break;
             case CCrmActivityType::Email:
                 //do nothing
                 break;
         }
     }
     $registerSonetEvent = isset($options['REGISTER_SONET_EVENT']) && $options['REGISTER_SONET_EVENT'] === true;
     $isSonetEventRegistred = false;
     if ($registerSonetEvent) {
         $isSonetEventSynchronized = self::SynchronizeLiveFeedEvent($ID, array('PROCESS_BINDINGS' => $bindingsChanged, 'BINDINGS' => $bindingsChanged ? $arBindings : null, 'REFRESH_DATE' => isset($arFields['COMPLETED']) && $arFields['COMPLETED'] !== $arPrevEntity['COMPLETED'], 'START_RESPONSIBLE_ID' => $arPrevEntity['RESPONSIBLE_ID'], 'FINAL_RESPONSIBLE_ID' => $responsibleID, 'EDITOR_ID' => intval($arFields["EDITOR_ID"]) > 0 ? $arFields["EDITOR_ID"] : CCrmSecurityHelper::GetCurrentUserID(), 'TYPE_ID' => $typeID, 'SUBJECT' => isset($arFields['SUBJECT']) ? $arFields['SUBJECT'] : $arPrevEntity['SUBJECT']));
         if (!$isSonetEventSynchronized) {
             $itemFields = self::GetByID($ID);
             if (is_array($itemFields)) {
                 $itemFields['BINDINGS'] = $arBindings;
                 $sonetEventID = self::RegisterLiveFeedEvent($itemFields);
                 $isSonetEventRegistred = is_int($sonetEventID) && $sonetEventID > 0;
                 if ($responsibleID > 0) {
                     CCrmSonetSubscription::RegisterSubscription(CCrmOwnerType::Activity, $ID, CCrmSonetSubscriptionType::Responsibility, $responsibleID);
                 }
             }
         }
     }
     if (!$isSonetEventRegistred && $responsibleID !== $prevResponsibleID) {
         CCrmSonetSubscription::ReplaceSubscriptionByEntity(CCrmOwnerType::Activity, $ID, CCrmSonetSubscriptionType::Responsibility, $responsibleID, $prevResponsibleID, $registerSonetEvent);
     }
     if ($storageElementsSerialized) {
         $arFields['STORAGE_ELEMENT_IDS'] = $storageElementIDs;
     }
     $rsEvents = GetModuleEvents('crm', 'OnActivityUpdate');
     while ($arEvent = $rsEvents->Fetch()) {
         ExecuteModuleEventEx($arEvent, array($ID, &$arFields));
     }
     if (defined("BX_COMP_MANAGED_CACHE")) {
         $GLOBALS["CACHE_MANAGER"]->ClearByTag("CRM_ACTIVITY_" . $ID);
     }
     return true;
 }
Esempio n. 2
0
 public function Add(array &$arFields, $bUpdateSearch = true, $options = array())
 {
     global $DB;
     if (!is_array($options)) {
         $options = array();
     }
     $this->LAST_ERROR = '';
     $iUserId = CCrmSecurityHelper::GetCurrentUserID();
     if (isset($arFields['ID'])) {
         unset($arFields['ID']);
     }
     if (isset($arFields['DATE_CREATE'])) {
         unset($arFields['DATE_CREATE']);
     }
     $arFields['~DATE_CREATE'] = $DB->CurrentTimeFunction();
     $arFields['~DATE_MODIFY'] = $DB->CurrentTimeFunction();
     if (!isset($arFields['CREATED_BY_ID']) || (int) $arFields['CREATED_BY_ID'] <= 0) {
         $arFields['CREATED_BY_ID'] = $iUserId;
     }
     if (!isset($arFields['MODIFY_BY_ID']) || (int) $arFields['MODIFY_BY_ID'] <= 0) {
         $arFields['MODIFY_BY_ID'] = $iUserId;
     }
     if (isset($arFields['ASSIGNED_BY_ID']) && is_array($arFields['ASSIGNED_BY_ID'])) {
         $arFields['ASSIGNED_BY_ID'] = count($arFields['ASSIGNED_BY_ID']) > 0 ? intval($arFields['ASSIGNED_BY_ID'][0]) : $iUserId;
     }
     if (!isset($arFields['ASSIGNED_BY_ID']) || (int) $arFields['ASSIGNED_BY_ID'] <= 0) {
         $arFields['ASSIGNED_BY_ID'] = $iUserId;
     }
     if (!$this->CheckFields($arFields, false, $options)) {
         $result = false;
         $arFields['RESULT_MESSAGE'] =& $this->LAST_ERROR;
     } else {
         if (!isset($arFields['STAGE_ID'])) {
             $arFields['STAGE_ID'] = 'NEW';
         }
         $arAttr = array();
         if (!empty($arFields['STAGE_ID'])) {
             $arAttr['STAGE_ID'] = $arFields['STAGE_ID'];
         }
         if (!empty($arFields['OPENED'])) {
             $arAttr['OPENED'] = $arFields['OPENED'];
         }
         $sPermission = 'ADD';
         if (isset($arFields['PERMISSION'])) {
             if ($arFields['PERMISSION'] == 'IMPORT') {
                 $sPermission = 'IMPORT';
             }
             unset($arFields['PERMISSION']);
         }
         if ($this->bCheckPermission) {
             $arEntityAttr = self::BuildEntityAttr($iUserId, $arAttr);
             $userPerms = $iUserId == CCrmPerms::GetCurrentUserID() ? $this->cPerms : CCrmPerms::GetUserPermissions($iUserId);
             $sEntityPerm = $userPerms->GetPermType('DEAL', $sPermission, $arEntityAttr);
             if ($sEntityPerm == BX_CRM_PERM_NONE) {
                 $this->LAST_ERROR = GetMessage('CRM_PERMISSION_DENIED');
                 $arFields['RESULT_MESSAGE'] =& $this->LAST_ERROR;
                 return false;
             }
             $assignedByID = intval($arFields['ASSIGNED_BY_ID']);
             if ($sEntityPerm == BX_CRM_PERM_SELF && $assignedByID != $iUserId) {
                 $arFields['ASSIGNED_BY_ID'] = $iUserId;
             }
             if ($sEntityPerm == BX_CRM_PERM_OPEN && $iUserId == $assignedByID) {
                 $arFields['OPENED'] = 'Y';
             }
         }
         $assignedByID = intval($arFields['ASSIGNED_BY_ID']);
         $arEntityAttr = self::BuildEntityAttr($assignedByID, $arAttr);
         $userPerms = $assignedByID == CCrmPerms::GetCurrentUserID() ? $this->cPerms : CCrmPerms::GetUserPermissions($assignedByID);
         $sEntityPerm = $userPerms->GetPermType('DEAL', $sPermission, $arEntityAttr);
         $this->PrepareEntityAttrs($arEntityAttr, $sEntityPerm);
         // Calculation of Account Data
         $accData = CCrmAccountingHelper::PrepareAccountingData(array('CURRENCY_ID' => isset($arFields['CURRENCY_ID']) ? $arFields['CURRENCY_ID'] : null, 'SUM' => isset($arFields['OPPORTUNITY']) ? $arFields['OPPORTUNITY'] : null, 'EXCH_RATE' => isset($arFields['EXCH_RATE']) ? $arFields['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'] : null, 'SUM' => isset($arFields['TAX_VALUE']) ? $arFields['TAX_VALUE'] : null, 'EXCH_RATE' => isset($arFields['EXCH_RATE']) ? $arFields['EXCH_RATE'] : null));
         if (is_array($accData)) {
             $arFields['TAX_VALUE_ACCOUNT'] = $accData['ACCOUNT_SUM'];
         }
         $now = ConvertTimeStamp(time(), 'SHORT', SITE_ID);
         $arFields['~BEGINDATE'] = $DB->CharToDateFunction(isset($arFields['BEGINDATE']) && $arFields['BEGINDATE'] !== '' ? $arFields['BEGINDATE'] : $now, 'SHORT', false);
         if (isset($arFields['BEGINDATE'])) {
             $arFields['__BEGINDATE'] = $arFields['BEGINDATE'];
             unset($arFields['BEGINDATE']);
         }
         $isFinalStage = self::GetStageSemantics($arFields['STAGE_ID']) !== 'process';
         $enableCloseDateSync = \Bitrix\Crm\Settings\DealSettings::isCloseDateSyncEnabled();
         $arFields['CLOSED'] = $isFinalStage ? 'Y' : 'N';
         if ($enableCloseDateSync && $isFinalStage) {
             $arFields['CLOSEDATE'] = $now;
             $arFields['~CLOSEDATE'] = $DB->CharToDateFunction($now, 'SHORT', false);
         } elseif ($isFinalStage && (!isset($arFields['CLOSEDATE']) || $arFields['CLOSEDATE'] === '')) {
             $arFields['CLOSEDATE'] = $now;
             $arFields['~CLOSEDATE'] = $DB->CharToDateFunction($now, 'SHORT', false);
         } elseif (isset($arFields['CLOSEDATE']) && $arFields['CLOSEDATE'] !== '') {
             $arFields['~CLOSEDATE'] = $DB->CharToDateFunction($arFields['CLOSEDATE'], 'SHORT', false);
         }
         if (isset($arFields['CLOSEDATE'])) {
             $arFields['__CLOSEDATE'] = $arFields['CLOSEDATE'];
             unset($arFields['CLOSEDATE']);
         }
         $beforeEvents = GetModuleEvents('crm', 'OnBeforeCrmDealAdd');
         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_CREATION_CANCELED', array('#NAME#' => $arEvent['TO_NAME']));
                     $arFields['RESULT_MESSAGE'] =& $this->LAST_ERROR;
                 }
                 return false;
             }
         }
         $ID = intval($DB->Add('b_crm_deal', $arFields, array(), 'FILE: ' . __FILE__ . '<br /> LINE: ' . __LINE__));
         //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']);
         }
         CCrmEntityHelper::NormalizeUserFields($arFields, self::$sUFEntityID, $GLOBALS['USER_FIELD_MANAGER'], array('IS_NEW' => true));
         $GLOBALS['USER_FIELD_MANAGER']->Update(self::$sUFEntityID, $ID, $arFields);
         CCrmPerms::UpdateEntityAttr('DEAL', $ID, $arEntityAttr);
         //Statistics & History -->
         Bitrix\Crm\Statistics\DealSumStatisticEntry::register($ID, $arFields);
         Bitrix\Crm\History\DealStageHistoryEntry::register($ID, $arFields, array('IS_NEW' => true));
         Bitrix\Crm\Statistics\DealInvoiceStatisticEntry::synchronize($ID, $arFields);
         //<-- Statistics & History
         if ($bUpdateSearch) {
             $arFilterTmp = array('ID' => $ID);
             if (!$this->bCheckPermission) {
                 $arFilterTmp["CHECK_PERMISSIONS"] = "N";
             }
             CCrmSearch::UpdateSearch($arFilterTmp, 'DEAL', true);
         }
         $result = $arFields['ID'] = $ID;
         if (isset($GLOBALS["USER"]) && isset($arFields['COMPANY_ID']) && intval($arFields['COMPANY_ID']) > 0) {
             if (!class_exists('CUserOptions')) {
                 include_once $_SERVER['DOCUMENT_ROOT'] . '/bitrix/modules/main/classes/' . $GLOBALS['DBType'] . '/favorites.php';
             }
             CUserOptions::SetOption('crm', 'crm_company_search', array('last_selected' => $arFields['COMPANY_ID']));
         }
         if (isset($GLOBALS["USER"]) && isset($arFields['CONTACT_ID']) && intval($arFields['CONTACT_ID']) > 0) {
             if (!class_exists('CUserOptions')) {
                 include_once $_SERVER['DOCUMENT_ROOT'] . "/bitrix/modules/main/classes/" . $GLOBALS['DBType'] . "/favorites.php";
             }
             CUserOptions::SetOption("crm", "crm_contact_search", array('last_selected' => $arFields['CONTACT_ID']));
         }
         if (isset($arFields['FM']) && is_array($arFields['FM'])) {
             $CCrmFieldMulti = new CCrmFieldMulti();
             $CCrmFieldMulti->SetFields('DEAL', $ID, $arFields['FM']);
         }
         if (isset($options['REGISTER_SONET_EVENT']) && $options['REGISTER_SONET_EVENT'] === true) {
             $opportunity = round(isset($arFields['OPPORTUNITY']) ? doubleval($arFields['OPPORTUNITY']) : 0.0, 2);
             $currencyID = isset($arFields['CURRENCY_ID']) ? $arFields['CURRENCY_ID'] : '';
             if ($currencyID === '') {
                 $currencyID = CCrmCurrency::GetBaseCurrencyID();
             }
             $assignedByID = intval($arFields['ASSIGNED_BY_ID']);
             $createdByID = intval($arFields['CREATED_BY_ID']);
             $liveFeedFields = array('USER_ID' => $createdByID, 'ENTITY_TYPE_ID' => CCrmOwnerType::Deal, 'ENTITY_ID' => $ID, 'TITLE' => GetMessage('CRM_DEAL_EVENT_ADD'), 'MESSAGE' => '', 'PARAMS' => array('TITLE' => isset($arFields['TITLE']) ? $arFields['TITLE'] : '', 'STAGE_ID' => isset($arFields['STAGE_ID']) ? $arFields['STAGE_ID'] : '', 'OPPORTUNITY' => strval($opportunity), 'CURRENCY_ID' => $currencyID, 'COMPANY_ID' => isset($arFields['COMPANY_ID']) ? intval($arFields['COMPANY_ID']) : 0, 'CONTACT_ID' => isset($arFields['CONTACT_ID']) ? intval($arFields['CONTACT_ID']) : 0, 'AUTHOR_ID' => intval($arFields['CREATED_BY_ID']), 'RESPONSIBLE_ID' => $assignedByID));
             //Register contact & company relations
             $contactID = isset($arFields['CONTACT_ID']) ? intval($arFields['CONTACT_ID']) : 0;
             $companyID = isset($arFields['COMPANY_ID']) ? intval($arFields['COMPANY_ID']) : 0;
             if ($contactID > 0 || $companyID > 0) {
                 $liveFeedFields['PARENTS'] = array();
                 if ($contactID > 0) {
                     $liveFeedFields['PARENTS'][] = array('ENTITY_TYPE_ID' => CCrmOwnerType::Contact, 'ENTITY_ID' => $contactID);
                 }
                 if ($companyID > 0) {
                     $liveFeedFields['PARENTS'][] = array('ENTITY_TYPE_ID' => CCrmOwnerType::Company, 'ENTITY_ID' => $companyID);
                 }
             }
             CCrmSonetSubscription::RegisterSubscription(CCrmOwnerType::Deal, $ID, CCrmSonetSubscriptionType::Responsibility, $assignedByID);
             $logEventID = CCrmLiveFeed::CreateLogEvent($liveFeedFields, CCrmLiveFeedEvent::Add);
             if ($logEventID && $assignedByID != $createdByID && 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", ""));
                 $arMessageFields = array("MESSAGE_TYPE" => IM_MESSAGE_SYSTEM, "TO_USER_ID" => $assignedByID, "FROM_USER_ID" => $createdByID, "NOTIFY_TYPE" => IM_NOTIFY_FROM, "NOTIFY_MODULE" => "crm", "LOG_ID" => $logEventID, "NOTIFY_EVENT" => "deal_add", "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);
             }
         }
         $afterEvents = GetModuleEvents('crm', 'OnAfterCrmDealAdd');
         while ($arEvent = $afterEvents->Fetch()) {
             ExecuteModuleEventEx($arEvent, array(&$arFields));
         }
         if (isset($arFields['ORIGIN_ID']) && $arFields['ORIGIN_ID'] !== '') {
             $afterEvents = GetModuleEvents('crm', 'OnAfterExternalCrmDealAdd');
             while ($arEvent = $afterEvents->Fetch()) {
                 ExecuteModuleEventEx($arEvent, array(&$arFields));
             }
         }
     }
     return $result;
 }
Esempio n. 3
0
 public function Add(array &$arFields, $bUpdateSearch = true, $arOptions = array())
 {
     global $DB;
     $this->LAST_ERROR = '';
     if (!is_array($arOptions)) {
         $arOptions = array();
     }
     if (isset($arOptions['CURRENT_USER'])) {
         $iUserId = intval($arOptions['CURRENT_USER']);
     } else {
         $iUserId = CCrmPerms::GetCurrentUserID();
     }
     if (isset($arFields['DATE_CREATE'])) {
         unset($arFields['DATE_CREATE']);
     }
     $arFields['~DATE_CREATE'] = $DB->CurrentTimeFunction();
     $arFields['~DATE_MODIFY'] = $DB->CurrentTimeFunction();
     if (!isset($arFields['CREATED_BY_ID']) || (int) $arFields['CREATED_BY_ID'] <= 0) {
         $arFields['CREATED_BY_ID'] = $iUserId;
     }
     if (!isset($arFields['MODIFY_BY_ID']) || (int) $arFields['MODIFY_BY_ID'] <= 0) {
         $arFields['MODIFY_BY_ID'] = $iUserId;
     }
     if (!isset($arFields['ASSIGNED_BY_ID']) || (int) $arFields['ASSIGNED_BY_ID'] <= 0) {
         $arFields['ASSIGNED_BY_ID'] = $iUserId;
     }
     if (!isset($arFields['OPPORTUNITY'])) {
         $arFields['OPPORTUNITY'] = 0.0;
     }
     if (!$this->CheckFields($arFields, false, $arOptions)) {
         $arFields['RESULT_MESSAGE'] =& $this->LAST_ERROR;
         return false;
     }
     if (isset($arFields['BIRTHDATE'])) {
         if ($arFields['BIRTHDATE'] !== '') {
             $birthDate = $arFields['BIRTHDATE'];
             $arFields['~BIRTHDATE'] = $DB->CharToDateFunction($birthDate, 'SHORT', false);
             $arFields['BIRTHDAY_SORT'] = \Bitrix\Crm\BirthdayReminder::prepareSorting($birthDate);
         } else {
             $arFields['BIRTHDAY_SORT'] = \Bitrix\Crm\BirthdayReminder::prepareSorting('');
         }
         unset($arFields['BIRTHDATE']);
     } else {
         $arFields['BIRTHDAY_SORT'] = \Bitrix\Crm\BirthdayReminder::prepareSorting('');
     }
     if (!isset($arFields['STATUS_ID']) || $arFields['STATUS_ID'] === '') {
         $arFields['STATUS_ID'] = 'NEW';
     }
     if (isset($arFields['DATE_CLOSED'])) {
         unset($arFields['DATE_CLOSED']);
     }
     self::EnsureStatusesLoaded();
     if (in_array($arFields['STATUS_ID'], self::$LEAD_STATUSES_BY_GROUP['FINISHED'])) {
         $arFields['~DATE_CLOSED'] = $DB->CurrentTimeFunction();
     }
     $arAttr = array();
     $arAttr['STATUS_ID'] = $arFields['STATUS_ID'];
     if (!empty($arFields['OPENED'])) {
         $arAttr['OPENED'] = $arFields['OPENED'];
     }
     $sPermission = 'ADD';
     if (isset($arFields['PERMISSION'])) {
         if ($arFields['PERMISSION'] == 'IMPORT') {
             $sPermission = 'IMPORT';
         }
         unset($arFields['PERMISSION']);
     }
     if ($this->bCheckPermission) {
         $arEntityAttr = self::BuildEntityAttr($iUserId, $arAttr);
         $userPerms = $iUserId == CCrmPerms::GetCurrentUserID() ? $this->cPerms : CCrmPerms::GetUserPermissions($iUserId);
         $sEntityPerm = $userPerms->GetPermType('LEAD', $sPermission, $arEntityAttr);
         if ($sEntityPerm == BX_CRM_PERM_NONE) {
             $this->LAST_ERROR = GetMessage('CRM_PERMISSION_DENIED');
             $arFields['RESULT_MESSAGE'] =& $this->LAST_ERROR;
             return false;
         }
         $assignedByID = intval($arFields['ASSIGNED_BY_ID']);
         if ($sEntityPerm == BX_CRM_PERM_SELF && $assignedByID != $iUserId) {
             $arFields['ASSIGNED_BY_ID'] = $iUserId;
         }
         if ($sEntityPerm == BX_CRM_PERM_OPEN && $iUserId == $assignedByID) {
             $arFields['OPENED'] = 'Y';
         }
     }
     $assignedByID = intval($arFields['ASSIGNED_BY_ID']);
     $arEntityAttr = self::BuildEntityAttr($assignedByID, $arAttr);
     $userPerms = $assignedByID == CCrmPerms::GetCurrentUserID() ? $this->cPerms : CCrmPerms::GetUserPermissions($assignedByID);
     $sEntityPerm = $userPerms->GetPermType('LEAD', $sPermission, $arEntityAttr);
     $this->PrepareEntityAttrs($arEntityAttr, $sEntityPerm);
     // Calculation of Account Data
     $accData = CCrmAccountingHelper::PrepareAccountingData(array('CURRENCY_ID' => isset($arFields['CURRENCY_ID']) ? $arFields['CURRENCY_ID'] : null, 'SUM' => isset($arFields['OPPORTUNITY']) ? $arFields['OPPORTUNITY'] : null, 'EXCH_RATE' => isset($arFields['EXCH_RATE']) ? $arFields['EXCH_RATE'] : null));
     if (is_array($accData)) {
         $arFields['ACCOUNT_CURRENCY_ID'] = $accData['ACCOUNT_CURRENCY_ID'];
         $arFields['OPPORTUNITY_ACCOUNT'] = $accData['ACCOUNT_SUM'];
     }
     if (isset($arFields['NAME']) || isset($arFields['LAST_NAME'])) {
         $arFields['FULL_NAME'] = trim((isset($arFields['NAME']) ? $arFields['NAME'] : '') . ' ' . (isset($arFields['LAST_NAME']) ? $arFields['LAST_NAME'] : ''));
     }
     $beforeEvents = GetModuleEvents('crm', 'OnBeforeCrmLeadAdd');
     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_LEAD_CREATION_CANCELED', array('#NAME#' => $arEvent['TO_NAME']));
                 $arFields['RESULT_MESSAGE'] =& $this->LAST_ERROR;
             }
             return false;
         }
     }
     $ID = intval($DB->Add('b_crm_lead', $arFields, array(), '', false, 'FILE: ' . __FILE__ . '<br /> LINE: ' . __LINE__));
     $arFields['ID'] = $ID;
     CCrmPerms::UpdateEntityAttr('LEAD', $ID, $arEntityAttr);
     $companyTitle = isset($arFields['COMPANY_TITLE']) ? $arFields['COMPANY_TITLE'] : '';
     if ($companyTitle !== '') {
         \Bitrix\Crm\Integrity\DuplicateOrganizationCriterion::register(CCrmOwnerType::Lead, $ID, $companyTitle);
     }
     $lastName = isset($arFields['LAST_NAME']) ? $arFields['LAST_NAME'] : '';
     if ($lastName !== '') {
         \Bitrix\Crm\Integrity\DuplicatePersonCriterion::register(CCrmOwnerType::Lead, $ID, $lastName, isset($arFields['NAME']) ? $arFields['NAME'] : '', isset($arFields['SECOND_NAME']) ? $arFields['SECOND_NAME'] : '');
     }
     \Bitrix\Crm\EntityAddress::register(CCrmOwnerType::Lead, $ID, \Bitrix\Crm\EntityAddress::Primary, array('ADDRESS_1' => isset($arFields['ADDRESS']) ? $arFields['ADDRESS'] : null, 'ADDRESS_2' => isset($arFields['ADDRESS_2']) ? $arFields['ADDRESS_2'] : null, 'CITY' => isset($arFields['ADDRESS_CITY']) ? $arFields['ADDRESS_CITY'] : null, 'POSTAL_CODE' => isset($arFields['ADDRESS_POSTAL_CODE']) ? $arFields['ADDRESS_POSTAL_CODE'] : null, 'REGION' => isset($arFields['ADDRESS_REGION']) ? $arFields['ADDRESS_REGION'] : null, 'PROVINCE' => isset($arFields['ADDRESS_PROVINCE']) ? $arFields['ADDRESS_PROVINCE'] : null, 'COUNTRY' => isset($arFields['ADDRESS_COUNTRY']) ? $arFields['ADDRESS_COUNTRY'] : null, 'COUNTRY_CODE' => isset($arFields['ADDRESS_COUNTRY_CODE']) ? $arFields['ADDRESS_COUNTRY_CODE'] : null));
     CCrmEntityHelper::NormalizeUserFields($arFields, self::$sUFEntityID, $GLOBALS['USER_FIELD_MANAGER'], array('IS_NEW' => true));
     $GLOBALS['USER_FIELD_MANAGER']->Update(self::$sUFEntityID, $ID, $arFields);
     if (isset($arFields['FM']) && is_array($arFields['FM'])) {
         $CCrmFieldMulti = new CCrmFieldMulti();
         $CCrmFieldMulti->SetFields('LEAD', $ID, $arFields['FM']);
         $emails = \Bitrix\Crm\Integrity\DuplicateCommunicationCriterion::extractMultifieldsValues($arFields['FM'], 'EMAIL');
         if (!empty($emails)) {
             \Bitrix\Crm\Integrity\DuplicateCommunicationCriterion::register(CCrmOwnerType::Lead, $ID, 'EMAIL', $emails);
         }
         $phones = \Bitrix\Crm\Integrity\DuplicateCommunicationCriterion::extractMultifieldsValues($arFields['FM'], 'PHONE');
         if (!empty($phones)) {
             \Bitrix\Crm\Integrity\DuplicateCommunicationCriterion::register(CCrmOwnerType::Lead, $ID, 'PHONE', $phones);
         }
     }
     \Bitrix\Crm\Integrity\DuplicateEntityRanking::registerEntityStatistics(CCrmOwnerType::Lead, $ID, $arFields);
     if ($bUpdateSearch) {
         CCrmSearch::UpdateSearch(array('ID' => $ID, 'CHECK_PERMISSIONS' => 'N'), 'LEAD', true);
     }
     if (isset($arOptions['REGISTER_SONET_EVENT']) && $arOptions['REGISTER_SONET_EVENT'] === true) {
         $opportunity = round(isset($arFields['OPPORTUNITY']) ? doubleval($arFields['OPPORTUNITY']) : 0.0, 2);
         $currencyID = isset($arFields['CURRENCY_ID']) ? $arFields['CURRENCY_ID'] : '';
         if ($currencyID === '') {
             $currencyID = CCrmCurrency::GetBaseCurrencyID();
         }
         $assignedByID = intval($arFields['ASSIGNED_BY_ID']);
         $createdByID = intval($arFields['CREATED_BY_ID']);
         $liveFeedFields = array('USER_ID' => $createdByID, 'ENTITY_TYPE_ID' => CCrmOwnerType::Lead, 'ENTITY_ID' => $ID, 'TITLE' => GetMessage('CRM_LEAD_EVENT_ADD'), 'MESSAGE' => '', 'PARAMS' => array('TITLE' => $arFields['TITLE'], 'NAME' => isset($arFields['NAME']) ? $arFields['NAME'] : '', 'SECOND_NAME' => isset($arFields['SECOND_NAME']) ? $arFields['SECOND_NAME'] : '', 'LAST_NAME' => isset($arFields['LAST_NAME']) ? $arFields['LAST_NAME'] : '', 'COMPANY_TITLE' => isset($arFields['COMPANY_TITLE']) ? $arFields['COMPANY_TITLE'] : '', 'STATUS_ID' => $arFields['STATUS_ID'], 'OPPORTUNITY' => strval($opportunity), 'CURRENCY_ID' => $currencyID, 'AUTHOR_ID' => intval($arFields['CREATED_BY_ID']), 'RESPONSIBLE_ID' => $assignedByID));
         CCrmSonetSubscription::RegisterSubscription(CCrmOwnerType::Lead, $ID, CCrmSonetSubscriptionType::Responsibility, $assignedByID);
         $logEventID = CCrmLiveFeed::CreateLogEvent($liveFeedFields, CCrmLiveFeedEvent::Add);
         if ($logEventID && $assignedByID != $createdByID && CModule::IncludeModule("im")) {
             $url = CCrmOwnerType::GetShowUrl(CCrmOwnerType::Lead, $ID);
             $serverName = (CMain::IsHTTPS() ? "https" : "http") . "://" . (defined("SITE_SERVER_NAME") && strlen(SITE_SERVER_NAME) > 0 ? SITE_SERVER_NAME : COption::GetOptionString("main", "server_name", ""));
             $arMessageFields = array("MESSAGE_TYPE" => IM_MESSAGE_SYSTEM, "TO_USER_ID" => $assignedByID, "FROM_USER_ID" => $createdByID, "NOTIFY_TYPE" => IM_NOTIFY_FROM, "NOTIFY_MODULE" => "crm", "LOG_ID" => $logEventID, "NOTIFY_EVENT" => "lead_add", "NOTIFY_TAG" => "CRM|LEAD|" . $ID, "NOTIFY_MESSAGE" => GetMessage("CRM_LEAD_RESPONSIBLE_IM_NOTIFY", array("#title#" => "<a href=\"" . $url . "\" class=\"bx-notifier-item-action\">" . htmlspecialcharsbx($arFields['TITLE']) . "</a>")), "NOTIFY_MESSAGE_OUT" => GetMessage("CRM_LEAD_RESPONSIBLE_IM_NOTIFY", array("#title#" => htmlspecialcharsbx($arFields['TITLE']))) . " (" . $serverName . $url . ")");
             CIMNotify::Add($arMessageFields);
         }
     }
     $afterEvents = GetModuleEvents('crm', 'OnAfterCrmLeadAdd');
     while ($arEvent = $afterEvents->Fetch()) {
         ExecuteModuleEventEx($arEvent, array(&$arFields));
     }
     if (isset($arFields['ORIGIN_ID']) && $arFields['ORIGIN_ID'] !== '') {
         $afterEvents = GetModuleEvents('crm', 'OnAfterExternalCrmLeadAdd');
         while ($arEvent = $afterEvents->Fetch()) {
             ExecuteModuleEventEx($arEvent, array(&$arFields));
         }
     }
     return $ID;
 }
Esempio n. 4
0
        $data['id'] = $ID;
        $info = CCrmEntitySelectorHelper::PrepareEntityInfo('COMPANY', $ID);
        echo CUtil::PhpToJSObject(array('DATA' => $data, 'INFO' => array('title' => $info['TITLE'], 'url' => $info['URL'])));
    } else {
        echo CUtil::PhpToJSObject(array('ERROR' => $CrmCompany->LAST_ERROR));
    }
} elseif ($action === 'ENABLE_SONET_SUBSCRIPTION') {
    $userID = CCrmSecurityHelper::GetCurrentUserID();
    $entityTypeName = isset($_POST['ENTITY_TYPE']) ? strtoupper($_POST['ENTITY_TYPE']) : '';
    $entityID = isset($_POST['ENTITY_ID']) ? intval($_POST['ENTITY_ID']) : 0;
    if ($userID > 0 && $entityTypeName === CCrmOwnerType::CompanyName && $entityID > 0 && CCrmCompany::CheckReadPermission($entityID)) {
        $isEnabled = CCrmSonetSubscription::IsRelationRegistered(CCrmOwnerType::Company, $entityID, CCrmSonetSubscriptionType::Observation, $userID);
        $enable = isset($_POST['ENABLE']) && strtoupper($_POST['ENABLE']) === 'Y';
        if ($isEnabled !== $enable) {
            if ($enable) {
                CCrmSonetSubscription::RegisterSubscription(CCrmOwnerType::Company, $entityID, CCrmSonetSubscriptionType::Observation, $userID);
            } else {
                CCrmSonetSubscription::UnRegisterSubscription(CCrmOwnerType::Company, $entityID, CCrmSonetSubscriptionType::Observation, $userID);
            }
        }
    }
} elseif ($action === 'FIND_DUPLICATES') {
    $userPermissions = CCrmPerms::GetCurrentUserPermissions();
    $params = isset($_POST['PARAMS']) && is_array($_POST['PARAMS']) ? $_POST['PARAMS'] : array();
    $entityTypeName = isset($params['ENTITY_TYPE_NAME']) ? $params['ENTITY_TYPE_NAME'] : '';
    if ($entityTypeName === '') {
        __CrmCompanyEditEndResonse(array('ERROR' => 'Entity type is not specified.'));
    }
    $entityTypeID = CCrmOwnerType::ResolveID($entityTypeName);
    if ($entityTypeID === CCrmOwnerType::Undefined) {
        __CrmCompanyEditEndResonse(array('ERROR' => 'Undefined entity type is specified.'));
Esempio n. 5
0
 public function Add(array &$arFields, $bUpdateSearch = true, $options = array())
 {
     global $DB;
     if (!is_array($options)) {
         $options = array();
     }
     $this->LAST_ERROR = '';
     $iUserId = CCrmSecurityHelper::GetCurrentUserID();
     if (isset($arFields['ID'])) {
         unset($arFields['ID']);
     }
     if (isset($arFields['DATE_CREATE'])) {
         unset($arFields['DATE_CREATE']);
     }
     $arFields['~DATE_CREATE'] = $DB->CurrentTimeFunction();
     $arFields['~DATE_MODIFY'] = $DB->CurrentTimeFunction();
     if (!isset($arFields['CREATED_BY_ID']) || intval($arFields['CREATED_BY_ID']) <= 0) {
         $arFields['CREATED_BY_ID'] = $iUserId;
     }
     if (!isset($arFields['MODIFY_BY_ID']) || intval($arFields['MODIFY_BY_ID']) <= 0) {
         $arFields['MODIFY_BY_ID'] = $iUserId;
     }
     if (!isset($arFields['ASSIGNED_BY_ID']) || intval($arFields['ASSIGNED_BY_ID']) <= 0) {
         $arFields['ASSIGNED_BY_ID'] = $iUserId;
     }
     if (isset($arFields['REVENUE'])) {
         $arFields['REVENUE'] = floatval($arFields['REVENUE']);
     }
     if (!$this->CheckFields($arFields, false, $options)) {
         $result = false;
         $arFields['RESULT_MESSAGE'] =& $this->LAST_ERROR;
     } else {
         $arAttr = array();
         if (!empty($arFields['OPENED'])) {
             $arAttr['OPENED'] = $arFields['OPENED'];
         }
         $sPermission = 'ADD';
         if (isset($arFields['PERMISSION'])) {
             if ($arFields['PERMISSION'] == 'IMPORT') {
                 $sPermission = 'IMPORT';
             }
             unset($arFields['PERMISSION']);
         }
         if ($this->bCheckPermission) {
             $arEntityAttr = self::BuildEntityAttr($iUserId, $arAttr);
             $userPerms = $iUserId == CCrmPerms::GetCurrentUserID() ? $this->cPerms : CCrmPerms::GetUserPermissions($iUserId);
             $sEntityPerm = $userPerms->GetPermType('COMPANY', $sPermission, $arEntityAttr);
             if ($sEntityPerm == BX_CRM_PERM_NONE) {
                 $this->LAST_ERROR = GetMessage('CRM_PERMISSION_DENIED');
                 $arFields['RESULT_MESSAGE'] =& $this->LAST_ERROR;
                 return false;
             }
             $assignedByID = intval($arFields['ASSIGNED_BY_ID']);
             if ($sEntityPerm == BX_CRM_PERM_SELF && $assignedByID != $iUserId) {
                 $arFields['ASSIGNED_BY_ID'] = $iUserId;
             }
             if ($sEntityPerm == BX_CRM_PERM_OPEN && $iUserId == $assignedByID) {
                 $arFields['OPENED'] = 'Y';
             }
         }
         $assignedByID = intval($arFields['ASSIGNED_BY_ID']);
         $arEntityAttr = self::BuildEntityAttr($assignedByID, $arAttr);
         $userPerms = $assignedByID == CCrmPerms::GetCurrentUserID() ? $this->cPerms : CCrmPerms::GetUserPermissions($assignedByID);
         $sEntityPerm = $userPerms->GetPermType('COMPANY', $sPermission, $arEntityAttr);
         $this->PrepareEntityAttrs($arEntityAttr, $sEntityPerm);
         if (isset($arFields['LOGO']) && is_array($arFields['LOGO']) && strlen(CFile::CheckImageFile($arFields['LOGO'])) === 0) {
             $arFields['LOGO']['MODULE_ID'] = 'crm';
             CFile::SaveForDB($arFields, 'LOGO', 'crm');
         }
         $beforeEvents = GetModuleEvents('crm', 'OnBeforeCrmCompanyAdd');
         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_COMPANY_CREATION_CANCELED', array('#NAME#' => $arEvent['TO_NAME']));
                     $arFields['RESULT_MESSAGE'] =& $this->LAST_ERROR;
                 }
                 return false;
             }
         }
         $ID = intval($DB->Add('b_crm_company', $arFields, array(), 'FILE: ' . __FILE__ . '<br /> LINE: ' . __LINE__));
         $result = $arFields['ID'] = $ID;
         CCrmPerms::UpdateEntityAttr('COMPANY', $ID, $arEntityAttr);
         \Bitrix\Crm\Integrity\DuplicateOrganizationCriterion::register(CCrmOwnerType::Company, $ID, $arFields['TITLE']);
         CCrmEntityHelper::NormalizeUserFields($arFields, self::$sUFEntityID, $GLOBALS['USER_FIELD_MANAGER'], array('IS_NEW' => true));
         $GLOBALS['USER_FIELD_MANAGER']->Update(self::$sUFEntityID, $ID, $arFields);
         if (isset($arFields['FM']) && is_array($arFields['FM'])) {
             $CCrmFieldMulti = new CCrmFieldMulti();
             $CCrmFieldMulti->SetFields('COMPANY', $ID, $arFields['FM']);
             $emails = \Bitrix\Crm\Integrity\DuplicateCommunicationCriterion::extractMultifieldsValues($arFields['FM'], 'EMAIL');
             if (!empty($emails)) {
                 \Bitrix\Crm\Integrity\DuplicateCommunicationCriterion::register(CCrmOwnerType::Company, $ID, 'EMAIL', $emails);
             }
             $phones = Bitrix\Crm\Integrity\DuplicateCommunicationCriterion::extractMultifieldsValues($arFields['FM'], 'PHONE');
             if (!empty($phones)) {
                 \Bitrix\Crm\Integrity\DuplicateCommunicationCriterion::register(CCrmOwnerType::Company, $ID, 'PHONE', $phones);
             }
         }
         \Bitrix\Crm\Integrity\DuplicateEntityRanking::registerEntityStatistics(CCrmOwnerType::Company, $ID, $arFields);
         if ($bUpdateSearch) {
             CCrmSearch::UpdateSearch(array('ID' => $ID, 'CHECK_PERMISSIONS' => 'N'), 'COMPANY', true);
         }
         if (isset($arFields['CONTACT_ID']) && is_array($arFields['CONTACT_ID'])) {
             $CCrmContact = new CCrmContact();
             $CCrmContact->UpdateCompanyId($arFields['CONTACT_ID'], $arFields['ID']);
             if (isset($GLOBALS["USER"])) {
                 if (!class_exists('CUserOptions')) {
                     include_once $_SERVER['DOCUMENT_ROOT'] . '/bitrix/modules/main/classes/' . $GLOBALS['DBType'] . '/favorites.php';
                 }
                 CUserOptions::SetOption('crm', 'crm_contact_search', array('last_selected' => implode(',', $arFields['CONTACT_ID'])));
             }
         }
         if (isset($options['REGISTER_SONET_EVENT']) && $options['REGISTER_SONET_EVENT'] === true) {
             $revenue = round(isset($arFields['REVENUE']) ? doubleval($arFields['REVENUE']) : 0.0, 2);
             $currencyID = isset($arFields['CURRENCY_ID']) ? $arFields['CURRENCY_ID'] : '';
             if ($currencyID === '') {
                 $currencyID = CCrmCurrency::GetBaseCurrencyID();
             }
             $multiFields = isset($arFields['FM']) ? $arFields['FM'] : null;
             $phones = CCrmFieldMulti::ExtractValues($multiFields, 'PHONE');
             $emails = CCrmFieldMulti::ExtractValues($multiFields, 'EMAIL');
             $assignedByID = intval($arFields['ASSIGNED_BY_ID']);
             $createdByID = intval($arFields['CREATED_BY_ID']);
             $liveFeedFields = array('USER_ID' => $createdByID, 'ENTITY_TYPE_ID' => CCrmOwnerType::Company, 'ENTITY_ID' => $ID, 'TITLE' => GetMessage('CRM_COMPANY_EVENT_ADD'), 'MESSAGE' => '', 'PARAMS' => array('TITLE' => $arFields['TITLE'], 'LOGO_ID' => isset($arFields['LOGO']) ? $arFields['LOGO'] : '', 'TYPE' => isset($arFields['COMPANY_TYPE']) ? $arFields['COMPANY_TYPE'] : '', 'REVENUE' => strval($revenue), 'CURRENCY_ID' => $currencyID, 'PHONES' => $phones, 'EMAILS' => $emails, 'AUTHOR_ID' => intval($arFields['CREATED_BY_ID']), 'RESPONSIBLE_ID' => $assignedByID));
             CCrmSonetSubscription::RegisterSubscription(CCrmOwnerType::Company, $ID, CCrmSonetSubscriptionType::Responsibility, $assignedByID);
             $logEventID = CCrmLiveFeed::CreateLogEvent($liveFeedFields, CCrmLiveFeedEvent::Add);
             if ($logEventID && $assignedByID != $createdByID && CModule::IncludeModule("im")) {
                 $url = CCrmOwnerType::GetShowUrl(CCrmOwnerType::Company, $ID);
                 $serverName = (CMain::IsHTTPS() ? "https" : "http") . "://" . (defined("SITE_SERVER_NAME") && strlen(SITE_SERVER_NAME) > 0 ? SITE_SERVER_NAME : COption::GetOptionString("main", "server_name", ""));
                 $arMessageFields = array("MESSAGE_TYPE" => IM_MESSAGE_SYSTEM, "TO_USER_ID" => $assignedByID, "FROM_USER_ID" => $createdByID, "NOTIFY_TYPE" => IM_NOTIFY_FROM, "NOTIFY_MODULE" => "crm", "LOG_ID" => $logEventID, "NOTIFY_EVENT" => "company_add", "NOTIFY_TAG" => "CRM|COMPANY_RESPONSIBLE|" . $ID, "NOTIFY_MESSAGE" => GetMessage("CRM_COMPANY_RESPONSIBLE_IM_NOTIFY", array("#title#" => "<a href=\"" . $url . "\" class=\"bx-notifier-item-action\">" . htmlspecialcharsbx($arFields['TITLE']) . "</a>")), "NOTIFY_MESSAGE_OUT" => GetMessage("CRM_COMPANY_RESPONSIBLE_IM_NOTIFY", array("#title#" => htmlspecialcharsbx($arFields['TITLE']))) . " (" . $serverName . $url . ")");
                 CIMNotify::Add($arMessageFields);
             }
         }
         $afterEvents = GetModuleEvents('crm', 'OnAfterCrmCompanyAdd');
         while ($arEvent = $afterEvents->Fetch()) {
             ExecuteModuleEventEx($arEvent, array(&$arFields));
         }
         if (isset($arFields['ORIGIN_ID']) && $arFields['ORIGIN_ID'] !== '') {
             $afterEvents = GetModuleEvents('crm', 'OnAfterExternalCrmCompanyAdd');
             while ($arEvent = $afterEvents->Fetch()) {
                 ExecuteModuleEventEx($arEvent, array(&$arFields));
             }
         }
     }
     return $result;
 }
Esempio n. 6
0
 public function Add($arFields, &$arRecalculated = false, $siteId = SITE_ID, $options = array())
 {
     /** @global \CDatabase $DB */
     global $DB;
     if (!CModule::IncludeModule('sale')) {
         return false;
     }
     if (!is_array($options)) {
         $options = array();
     }
     $bRecalculate = is_array($arRecalculated);
     $orderID = false;
     $tmpOrderId = intval($arFields['ID']) <= 0 ? 0 : $arFields['ID'];
     if (isset($arFields['ID'])) {
         unset($arFields['ID']);
     }
     $arPrevOrder = $tmpOrderId !== 0 ? CCrmInvoice::GetByID($tmpOrderId) : null;
     $userId = CCrmSecurityHelper::GetCurrentUserID();
     if (!isset($arFields['RESPONSIBLE_ID']) || (int) $arFields['RESPONSIBLE_ID'] <= 0) {
         if (is_array($arPrevOrder) && isset($arPrevOrder['RESPONSIBLE_ID']) && intval($arPrevOrder['RESPONSIBLE_ID']) > 0) {
             $arFields['RESPONSIBLE_ID'] = $arPrevOrder['RESPONSIBLE_ID'];
         } else {
             $arFields['RESPONSIBLE_ID'] = $userId;
         }
     }
     $orderStatus = '';
     if (isset($arFields['STATUS_ID'])) {
         $orderStatus = $arFields['STATUS_ID'];
         unset($arFields['STATUS_ID']);
     }
     // prepare entity permissions
     $arAttr = array();
     if (!empty($arFields['OPENED'])) {
         $arAttr['OPENED'] = $arFields['OPENED'];
     }
     $sPermission = $tmpOrderId > 0 ? 'WRITE' : 'ADD';
     if ($this->bCheckPermission) {
         $arEntityAttr = self::BuildEntityAttr($userId, $arAttr);
         $userPerms = $userId == CCrmPerms::GetCurrentUserID() ? $this->cPerms : CCrmPerms::GetUserPermissions($userId);
         $sEntityPerm = $userPerms->GetPermType('INVOICE', $sPermission, $arEntityAttr);
         if ($sEntityPerm == BX_CRM_PERM_NONE) {
             $this->LAST_ERROR = GetMessage('CRM_PERMISSION_DENIED');
             $GLOBALS['APPLICATION']->ThrowException($this->LAST_ERROR);
             return false;
         }
         $responsibleID = intval($arFields['RESPONSIBLE_ID']);
         if ($sEntityPerm == BX_CRM_PERM_SELF && $responsibleID != $userId) {
             $arFields['RESPONSIBLE_ID'] = $userId;
         }
         if ($sEntityPerm == BX_CRM_PERM_OPEN && $userId == $responsibleID) {
             $arFields['OPENED'] = 'Y';
         }
     }
     $responsibleID = intval($arFields['RESPONSIBLE_ID']);
     $arEntityAttr = self::BuildEntityAttr($responsibleID, $arAttr);
     $userPerms = $responsibleID == CCrmPerms::GetCurrentUserID() ? $this->cPerms : CCrmPerms::GetUserPermissions($responsibleID);
     $sEntityPerm = $userPerms->GetPermType('INVOICE', $sPermission, $arEntityAttr);
     $this->PrepareEntityAttrs($arEntityAttr, $sEntityPerm);
     // date fields
     if ($tmpOrderId === 0) {
         $arFields['~DATE_BILL'] = $DB->CharToDateFunction(isset($arFields['DATE_BILL']) && $arFields['DATE_BILL'] !== '' ? $arFields['DATE_BILL'] : ConvertTimeStamp(time(), 'SHORT', SITE_ID), 'SHORT', false);
     } else {
         if (isset($arFields['DATE_BILL']) && $arFields['DATE_BILL'] !== '') {
             $arFields['~DATE_BILL'] = $DB->CharToDateFunction($arFields['DATE_BILL'], 'SHORT', false);
         }
     }
     unset($arFields['DATE_BILL']);
     if (isset($arFields['DATE_PAY_BEFORE']) && $arFields['DATE_PAY_BEFORE'] !== '') {
         $arFields['~DATE_PAY_BEFORE'] = $DB->CharToDateFunction($arFields['DATE_PAY_BEFORE'], 'SHORT', false);
     }
     unset($arFields['DATE_PAY_BEFORE']);
     if ($tmpOrderId !== 0 && !isset($arFields['PRODUCT_ROWS']) && !isset($arFields['INVOICE_PROPERTIES'])) {
         if (!is_array($arPrevOrder)) {
             return false;
         }
         $prevResponsibleID = isset($arPrevOrder['RESPONSIBLE_ID']) ? intval($arPrevOrder['RESPONSIBLE_ID']) : 0;
         $responsibleID = isset($arFields['RESPONSIBLE_ID']) ? intval($arFields['RESPONSIBLE_ID']) : 0;
         $prevStatusID = isset($arPrevOrder['STATUS_ID']) ? $arPrevOrder['STATUS_ID'] : '';
         // simple update order fields
         $CSaleOrder = new CSaleOrder();
         $orderID = $CSaleOrder->Update($tmpOrderId, $arFields);
         CCrmEntityHelper::NormalizeUserFields($arFields, self::$sUFEntityID, $GLOBALS['USER_FIELD_MANAGER'], array('IS_NEW' => false));
         $GLOBALS['USER_FIELD_MANAGER']->Update(self::$sUFEntityID, $tmpOrderId, $arFields);
         $registerSonetEvent = isset($options['REGISTER_SONET_EVENT']) && $options['REGISTER_SONET_EVENT'] === true;
         if (is_int($orderID) && $orderID > 0) {
             if ($registerSonetEvent) {
                 $newDealID = isset($arFields['UF_DEAL_ID']) ? intval($arFields['UF_DEAL_ID']) : 0;
                 $oldDealID = isset($arPrevOrder['UF_DEAL_ID']) ? intval($arPrevOrder['UF_DEAL_ID']) : 0;
                 $newCompanyID = isset($arFields['UF_COMPANY_ID']) ? intval($arFields['UF_COMPANY_ID']) : 0;
                 $oldCompanyID = isset($arPrevOrder['UF_COMPANY_ID']) ? intval($arPrevOrder['UF_COMPANY_ID']) : 0;
                 $newContactID = isset($arFields['UF_CONTACT_ID']) ? intval($arFields['UF_CONTACT_ID']) : 0;
                 $oldContactID = isset($arPrevOrder['UF_CONTACT_ID']) ? intval($arPrevOrder['UF_CONTACT_ID']) : 0;
                 $parents = array();
                 $parentsChanged = $newDealID !== $oldDealID || $newCompanyID !== $oldCompanyID || $newContactID !== $oldContactID;
                 if ($parentsChanged) {
                     if ($newDealID > 0) {
                         $parents[] = array('ENTITY_TYPE_ID' => CCrmOwnerType::Deal, 'ENTITY_ID' => $newDealID);
                     }
                     if ($newCompanyID > 0) {
                         $parents[] = array('ENTITY_TYPE_ID' => CCrmOwnerType::Company, 'ENTITY_ID' => $newCompanyID);
                     }
                     if ($newContactID > 0) {
                         $parents[] = array('ENTITY_TYPE_ID' => CCrmOwnerType::Contact, 'ENTITY_ID' => $newContactID);
                     }
                 }
                 $oldOrderStatus = isset($arPrevOrder['STATUS_ID']) ? $arPrevOrder['STATUS_ID'] : '';
                 self::SynchronizeLiveFeedEvent($orderID, array('PROCESS_PARENTS' => $parentsChanged, 'PARENTS' => $parents, 'REFRESH_DATE' => $orderStatus !== $oldOrderStatus, 'START_RESPONSIBLE_ID' => $prevResponsibleID, 'FINAL_RESPONSIBLE_ID' => $responsibleID, 'TOPIC' => isset($arPrevOrder['ORDER_TOPIC']) ? $arPrevOrder['ORDER_TOPIC'] : $orderID));
             }
             if ($responsibleID !== $prevResponsibleID) {
                 CCrmSonetSubscription::ReplaceSubscriptionByEntity(CCrmOwnerType::Invoice, $orderID, CCrmSonetSubscriptionType::Responsibility, $responsibleID, $prevResponsibleID, $registerSonetEvent);
             }
         }
     } else {
         // check product rows
         if (!isset($arFields['PRODUCT_ROWS']) || !is_array($arFields['PRODUCT_ROWS']) || count($arFields['PRODUCT_ROWS']) <= 0) {
             return false;
         }
         $arProduct = $arFields['PRODUCT_ROWS'];
         // prepare shopping cart data
         // <editor-fold defaultstate="collapsed" desc="prepare shopping cart data ...">
         // get xml_id fields
         $catalogXmlId = CCrmCatalog::GetDefaultCatalogXmlId();
         $arNewProducts = array();
         $bGetBasketXmlIds = false;
         foreach ($arProduct as &$productRow) {
             if (isset($productRow['ID']) && intval($productRow['ID']) === 0 && isset($productRow['PRODUCT_ID'])) {
                 $arNewProducts[] = $productRow['PRODUCT_ID'];
             } else {
                 $bGetBasketXmlIds = true;
             }
         }
         unset($productRow);
         $arXmlIds = array();
         $oldProductRows = null;
         if ($bGetBasketXmlIds && intval($tmpOrderId) > 0) {
             $oldProductRows = CCrmInvoice::GetProductRows($tmpOrderId);
             if (count($oldProductRows) > 0) {
                 foreach ($oldProductRows as $row) {
                     $arXmlIds[intval($row['ID'])][$row['PRODUCT_ID']] = array('CATALOG_XML_ID' => $row['CATALOG_XML_ID'], 'PRODUCT_XML_ID' => $row['PRODUCT_XML_ID']);
                 }
                 unset($row);
             }
         }
         unset($bGetBasketXmlIds);
         if (count($arNewProducts) > 0) {
             $dbRes = CCrmProduct::GetList(array(), array('ID' => $arNewProducts), array('ID', 'XML_ID'));
             while ($row = $dbRes->Fetch()) {
                 $arXmlIds[0][$row['ID']] = array('CATALOG_XML_ID' => $catalogXmlId, 'PRODUCT_XML_ID' => $row['XML_ID']);
             }
             unset($dbRes, $row);
         }
         unset($arNewProducts, $arOldProducts);
         // products without measures
         $productMeasures = array();
         $productId = 0;
         $productIds = array();
         foreach ($arProduct as $productRow) {
             $productId = intval($productRow['PRODUCT_ID']);
             if ($productId > 0 && (!array_key_exists('MEASURE_CODE', $productRow) || intval($productRow['MEASURE_CODE']) <= 0)) {
                 $productIds[] = $productId;
             }
         }
         unset($productId, $productRow);
         if (count($productIds) > 0) {
             $productMeasures = \Bitrix\Crm\Measure::getProductMeasures($productIds);
         }
         unset($productIds);
         $currencyId = CCrmInvoice::GetCurrencyID($siteId);
         $i = 0;
         $defaultMeasure = null;
         $oldProductRowsById = null;
         foreach ($arProduct as &$productRow) {
             $productXmlId = $catalogXmlId = null;
             $rowIndex = intval($productRow['ID']);
             $productId = $productRow['PRODUCT_ID'];
             $isCustomized = isset($productRow['CUSTOMIZED']) && $productRow['CUSTOMIZED'] === 'Y';
             $productRow['MODULE'] = $productRow['PRODUCT_PROVIDER_CLASS'] = '';
             if ($productId > 0) {
                 if (!$isCustomized) {
                     $productRow['MODULE'] = 'catalog';
                     $productRow['PRODUCT_PROVIDER_CLASS'] = 'CCatalogProductProvider';
                 }
                 if (is_array($arXmlIds[$rowIndex]) && isset($arXmlIds[$rowIndex][$productId])) {
                     $catalogXmlId = $arXmlIds[$rowIndex][$productId]['CATALOG_XML_ID'];
                     $productXmlId = $arXmlIds[$rowIndex][$productId]['PRODUCT_XML_ID'];
                 }
                 $productRow['CATALOG_XML_ID'] = $catalogXmlId;
                 $productRow['PRODUCT_XML_ID'] = $productXmlId;
             } else {
                 $productRow["PRODUCT_XML_ID"] = "CRM-" . randString(8);
                 $ri = new \Bitrix\Main\Type\RandomSequence($productRow["PRODUCT_XML_ID"]);
                 $productRow["PRODUCT_ID"] = $ri->rand(1000000, 9999999);
                 $productRow['CATALOG_XML_ID'] = '';
             }
             if ($isCustomized) {
                 $productRow['CUSTOM_PRICE'] = 'Y';
             }
             if (isset($productRow['PRODUCT_NAME'])) {
                 $productRow['NAME'] = $productRow['PRODUCT_NAME'];
                 unset($productRow['PRODUCT_NAME']);
             }
             if (isset($productRow['PRICE'])) {
                 $productRow['PRICE_DEFAULT'] = $productRow['PRICE'];
             }
             if (!isset($productRow['CURRENCY'])) {
                 $productRow['CURRENCY'] = $currencyId;
             }
             // measures
             $bRefreshMeasureName = false;
             if (!array_key_exists('MEASURE_CODE', $productRow) || intval($productRow['MEASURE_CODE'] <= 0)) {
                 if ($oldProductRows === null && $tmpOrderId > 0) {
                     $oldProductRows = CCrmInvoice::GetProductRows($tmpOrderId);
                 }
                 if (is_array($oldProductRows) && count($oldProductRows) > 0 && $oldProductRowsById === null) {
                     $oldProductRowsById = array();
                     foreach ($oldProductRows as $row) {
                         $oldProductRowsById[intval($row['ID'])] = $row;
                     }
                     unset($row);
                 }
                 if (is_array($oldProductRowsById) && isset($oldProductRowsById[$rowIndex])) {
                     $row = $oldProductRowsById[$rowIndex];
                     if (intval($productId) === intval($row['PRODUCT_ID'])) {
                         if (isset($row['MEASURE_CODE'])) {
                             $productRow['MEASURE_CODE'] = $row['MEASURE_CODE'];
                         }
                         if (isset($row['MEASURE_NAME'])) {
                             $productRow['MEASURE_NAME'] = $row['MEASURE_NAME'];
                         } else {
                             $bRefreshMeasureName = true;
                         }
                         unset($row);
                     }
                 }
             }
             if (!isset($productRow['MEASURE_CODE']) || intval($productRow['MEASURE_CODE']) <= 0) {
                 if ($productId > 0 && isset($productMeasures[$productId])) {
                     $measure = is_array($productMeasures[$productId][0]) ? $productMeasures[$productId][0] : null;
                     if (is_array($measure)) {
                         if (isset($measure['CODE'])) {
                             $productRow['MEASURE_CODE'] = $measure['CODE'];
                         }
                         if (isset($measure['SYMBOL'])) {
                             $productRow['MEASURE_NAME'] = $measure['SYMBOL'];
                         }
                     }
                     unset($measure);
                 }
             }
             if (!isset($productRow['MEASURE_CODE']) || intval($productRow['MEASURE_CODE']) <= 0) {
                 if ($defaultMeasure === null) {
                     $defaultMeasure = \Bitrix\Crm\Measure::getDefaultMeasure();
                 }
                 if (is_array($defaultMeasure)) {
                     $productRow['MEASURE_CODE'] = $defaultMeasure['CODE'];
                     $productRow['MEASURE_NAME'] = $defaultMeasure['SYMBOL'];
                 }
             }
             if (isset($productRow['MEASURE_CODE']) && intval($productRow['MEASURE_CODE']) > 0 && ($bRefreshMeasureName || !array_key_exists('MEASURE_NAME', $productRow) || empty($productRow['MEASURE_NAME']))) {
                 $measure = \Bitrix\Crm\Measure::getMeasureByCode($productRow['MEASURE_CODE']);
                 if (is_array($measure) && isset($measure['SYMBOL'])) {
                     $productRow['MEASURE_NAME'] = $measure['SYMBOL'];
                 }
                 unset($measure);
             }
             $i++;
         }
         unset($productRow, $productMeasures, $catalogXmlId, $productXmlId);
         $arOrderProductPrice = self::__fGetUserShoppingCart($arProduct, $siteId, 'N');
         foreach ($arOrderProductPrice as &$arItem) {
             $arItem["ID_TMP"] = $arItem["ID"];
             $arItem["NAME_TMP"] = $arItem["NAME"];
             unset($arItem["ID"]);
         }
         unset($arItem);
         // user id for order
         $saleUserId = intval(CSaleUser::GetAnonymousUserID());
         if ($saleUserId <= 0) {
             return false;
         }
         $arErrors = array();
         $arShoppingCart = CSaleBasket::DoGetUserShoppingCart($siteId, $saleUserId, $arOrderProductPrice, $arErrors, array(), $tmpOrderId);
         if (!is_array($arShoppingCart) || count($arShoppingCart) === 0) {
             $GLOBALS['APPLICATION']->ThrowException(GetMessage('CRM_ERROR_EMPTY_INVOICE_SPEC'));
             return false;
         }
         foreach ($arShoppingCart as $key => &$arItem) {
             $arItem["ID"] = $arItem["ID_TMP"];
             $arItem["NAME"] = $arItem["NAME_TMP"];
             unset($arItem["NAME_TMP"], $arItem["ID_TMP"]);
             //$arShoppingCart[$key]["ID"] = $arItem["ID"];
         }
         unset($key, $arItem);
         // </editor-fold>
         // person type
         $personTypeId = 0;
         if (!isset($arFields['PERSON_TYPE_ID']) || intval($arFields['PERSON_TYPE_ID']) <= 0) {
             $arPersonTypes = CCrmPaySystem::getPersonTypeIDs();
             if (isset($arPersonTypes['CONTACT'])) {
                 $personTypeId = intval($arPersonTypes['CONTACT']);
             }
         } else {
             $personTypeId = $arFields['PERSON_TYPE_ID'];
         }
         if ($personTypeId <= 0) {
             return false;
         }
         // preparing order to save
         // <editor-fold defaultstate="collapsed" desc="preparing order to save ...">
         $arOrderPropsValues = array();
         if (isset($arFields['INVOICE_PROPERTIES']) && is_array($arFields['INVOICE_PROPERTIES']) && count($arFields['INVOICE_PROPERTIES']) > 0) {
             $arOrderPropsValues = $arFields['INVOICE_PROPERTIES'];
         }
         if (isset($arFields['INVOICE_PROPERTIES'])) {
             unset($arFields['INVOICE_PROPERTIES']);
         }
         if (count($arOrderPropsValues) <= 0) {
             return false;
         }
         $deliveryId = null;
         $paySystemId = $arFields['PAY_SYSTEM_ID'];
         $arOptions = array('LOCATION_IN_CODES' => true);
         // let DoCalculateOrder know we send location in CODEs
         $arErrors = $arWarnings = array();
         $CSaleOrder = new CSaleOrder();
         $arOrder = $CSaleOrder->DoCalculateOrder($siteId, $saleUserId, $arShoppingCart, $personTypeId, $arOrderPropsValues, $deliveryId, $paySystemId, $arOptions, $arErrors, $arWarnings);
         if (count($arOrder) <= 0) {
             return false;
         }
         // </editor-fold>
         if ($bRecalculate) {
             foreach ($arOrder as $k => $v) {
                 $arRecalculated[$k] = $v;
             }
             return true;
         }
         // merge order fields
         $arAdditionalFields = array();
         foreach ($arFields as $k => $v) {
             if ($k === 'PRODUCT_ROWS') {
                 continue;
             }
             $arAdditionalFields[$k] = $v;
         }
         $arOrder['LOCATION_IN_CODES'] = true;
         // let DoSaveOrder know we send location in IDs
         // saving order
         $arErrors = array();
         $orderID = $CSaleOrder->DoSaveOrder($arOrder, $arAdditionalFields, $tmpOrderId, $arErrors);
         if (is_int($orderID) && $orderID > 0) {
             CCrmEntityHelper::NormalizeUserFields($arFields, self::$sUFEntityID, $GLOBALS['USER_FIELD_MANAGER'], array('IS_NEW' => $tmpOrderId === 0));
             $GLOBALS['USER_FIELD_MANAGER']->Update(self::$sUFEntityID, $orderID, $arFields);
         }
         if (is_int($orderID) && $orderID > 0 && isset($options['REGISTER_SONET_EVENT']) && $options['REGISTER_SONET_EVENT'] === true) {
             $prevResponsibleID = is_array($arPrevOrder) && isset($arPrevOrder['RESPONSIBLE_ID']) ? intval($arPrevOrder['RESPONSIBLE_ID']) : 0;
             $responsibleID = isset($arFields['RESPONSIBLE_ID']) ? intval($arFields['RESPONSIBLE_ID']) : 0;
             if ($tmpOrderId <= 0) {
                 self::RegisterLiveFeedEvent($arFields, $orderID, $userId);
                 if ($responsibleID > 0) {
                     CCrmSonetSubscription::RegisterSubscription(CCrmOwnerType::Invoice, $orderID, CCrmSonetSubscriptionType::Responsibility, $responsibleID);
                 }
             } else {
                 $newDealID = isset($arFields['UF_DEAL_ID']) ? intval($arFields['UF_DEAL_ID']) : 0;
                 $oldDealID = isset($arPrevOrder['UF_DEAL_ID']) ? intval($arPrevOrder['UF_DEAL_ID']) : 0;
                 $newCompanyID = isset($arFields['UF_COMPANY_ID']) ? intval($arFields['UF_COMPANY_ID']) : 0;
                 $oldCompanyID = isset($arPrevOrder['UF_COMPANY_ID']) ? intval($arPrevOrder['UF_COMPANY_ID']) : 0;
                 $newContactID = isset($arFields['UF_CONTACT_ID']) ? intval($arFields['UF_CONTACT_ID']) : 0;
                 $oldContactID = isset($arPrevOrder['UF_CONTACT_ID']) ? intval($arPrevOrder['UF_CONTACT_ID']) : 0;
                 $parents = array();
                 $parentsChanged = $newDealID !== $oldDealID || $newCompanyID !== $oldCompanyID || $newContactID !== $oldContactID;
                 if ($parentsChanged) {
                     if ($newDealID > 0) {
                         $parents[] = array('ENTITY_TYPE_ID' => CCrmOwnerType::Deal, 'ENTITY_ID' => $newDealID);
                     }
                     if ($newCompanyID > 0) {
                         $parents[] = array('ENTITY_TYPE_ID' => CCrmOwnerType::Company, 'ENTITY_ID' => $newCompanyID);
                     }
                     if ($newContactID > 0) {
                         $parents[] = array('ENTITY_TYPE_ID' => CCrmOwnerType::Contact, 'ENTITY_ID' => $newContactID);
                     }
                 }
                 $oldOrderStatus = isset($arPrevOrder['STATUS_ID']) ? $arPrevOrder['STATUS_ID'] : '';
                 self::SynchronizeLiveFeedEvent($orderID, array('PROCESS_PARENTS' => $parentsChanged, 'PARENTS' => $parents, 'REFRESH_DATE' => $orderStatus !== $oldOrderStatus, 'START_RESPONSIBLE_ID' => $prevResponsibleID, 'FINAL_RESPONSIBLE_ID' => $responsibleID, 'TOPIC' => isset($arPrevOrder['ORDER_TOPIC']) ? $arPrevOrder['ORDER_TOPIC'] : $orderID));
                 if ($responsibleID !== $prevResponsibleID) {
                     CCrmSonetSubscription::ReplaceSubscriptionByEntity(CCrmOwnerType::Invoice, $orderID, CCrmSonetSubscriptionType::Responsibility, $responsibleID, $prevResponsibleID, true);
                 }
             }
         }
     }
     if (intval($orderID) > 0 && !empty($orderStatus)) {
         // set status
         $this->SetStatus($orderID, $orderStatus);
         // update entity permissions
         CCrmPerms::UpdateEntityAttr('INVOICE', $orderID, $arEntityAttr);
         $newDealID = isset($arFields['UF_DEAL_ID']) ? (int) $arFields['UF_DEAL_ID'] : 0;
         $oldDealID = is_array($arPrevOrder) && isset($arPrevOrder['UF_DEAL_ID']) ? (int) $arPrevOrder['UF_DEAL_ID'] : 0;
         if ($newDealID) {
             Bitrix\Crm\Statistics\DealInvoiceStatisticEntry::register($newDealID);
         }
         if ($oldDealID > 0 && $oldDealID !== $newDealID) {
             Bitrix\Crm\Statistics\DealInvoiceStatisticEntry::register($oldDealID);
         }
         if (isset($options['UPDATE_SEARCH']) && $options['UPDATE_SEARCH'] === true) {
             $arFilterTmp = array('ID' => $orderID);
             if (!$this->bCheckPermission) {
                 $arFilterTmp["CHECK_PERMISSIONS"] = "N";
             }
             CCrmSearch::UpdateSearch($arFilterTmp, 'INVOICE', true);
         }
     }
     return $orderID;
 }