require_once "company.demo.php"; $CCrmCompany = new CCrmCompany(); foreach ($arCompany as $ID => $arParams) { $arCompany[$ID]['ID'] = $CCrmCompany->Add($arParams); } // Add Deal require_once "deal.demo.php"; $CCrmDeal = new CCrmDeal(); foreach ($arDeals as $ID => &$arParams) { $arProductRows = null; if (isset($arParams['PRODUCT_ROWS'])) { $arProductRows = $arParams['PRODUCT_ROWS']; unset($arParams['PRODUCT_ROWS']); } $arParams['CURRENCY_ID'] = $currencyID; $dealID = $CCrmDeal->Add($arParams); $arDeals[$ID]['ID'] = $dealID; if (is_array($arProductRows)) { foreach ($arProductRows as &$arProductRow) { $originID = $arProductRow['ORIGIN_ID']; $arProduct = CCrmProduct::GetByOriginID($originID, $catalogID); if (!is_array($arProduct)) { continue; } CCrmDeal::SaveProductRows($dealID, array(array('PRODUCT_ID' => intval($arProduct['ID']), 'PRICE' => doubleval($arProduct['PRICE']), 'QUANTITY' => 1))); } } } // Add event require_once "event.demo.php"; $CCrmEvent = new CCrmEvent();
$fields['TAX_VALUE'] = isset($result['TAX_VALUE']) ? $result['TAX_VALUE'] : 0.0; } } $assignedByID = isset($data['ASSIGNED_BY_ID']) ? intval($data['ASSIGNED_BY_ID']) : 0; if ($assignedByID <= 0) { $assignedByID = intval($curUser->GetID()); } $fields['ASSIGNED_BY_ID'] = $assignedByID; $entity = new CCrmDeal(false); if (!$entity->CheckFields($fields, !$isNew ? $ID : false, array('DISABLE_USER_FIELD_CHECK' => true))) { __CrmMobileDealEditEndResonse(array('ERROR' => strip_tags(preg_replace("/<br[^>]*>/", "\n", $entity->LAST_ERROR)))); } else { //$DB->StartTransaction(); $successed = false; if ($isNew) { $ID = $entity->Add($fields, true, array('DISABLE_USER_FIELD_CHECK' => true, 'REGISTER_SONET_EVENT' => true)); $successed = $ID !== false; } else { $successed = $entity->Update($ID, $fields, true, true, array('DISABLE_USER_FIELD_CHECK' => true, 'REGISTER_SONET_EVENT' => true)); } if ($successed && $processProductRows && (!$isNew || !empty($productRows))) { $successed = CCrmDeal::SaveProductRows($ID, $productRows, false, true, false); if (!$successed) { $fields['RESULT_MESSAGE'] = 'Could not save product rows.'; } } if ($successed) { //$DB->Commit(); $errors = array(); CCrmBizProcHelper::AutoStartWorkflows(CCrmOwnerType::Deal, $ID, $isNew ? CCrmBizProcEventType::Create : CCrmBizProcEventType::Edit, $errors); $dbRes = CCrmDeal::GetListEx(array(), array('=ID' => $ID, 'CHECK_PERMISSIONS' => 'N'));
private function SaveOrderDataDeal($arOrder, $contactId = null, $companyId = null) { $dealId = 0; $dealTitle = ""; $dbDeal = CCrmDeal::GetList(array(), array("ORIGINATOR_ID" => $this->externalSaleId, "ORIGIN_ID" => $arOrder["ID"], "CHECK_PERMISSIONS" => "N")); if ($arDeal = $dbDeal->Fetch()) { $dealId = $arDeal["ID"]; $dealTitle = $arDeal["TITLE"]; } $newDeal = $dealId == 0; if ($this->arExternalSale == null) { $this->arExternalSale = CCrmExternalSale::GetDefaultSettings($this->externalSaleId); } $arFields = array('ORIGINATOR_ID' => $this->externalSaleId, 'ORIGIN_ID' => $arOrder["ID"], 'BEGINDATE' => $arOrder["DATE_INSERT"], 'CURRENCY_ID' => $arOrder["CURRENCY"], 'EXCH_RATE' => $arOrder["CURRENCY_RATE"], 'OPPORTUNITY' => $arOrder["PRICE"]); // Prevent reset comment if order comment is empty if (isset($arOrder["COMMENT"]) && $arOrder["COMMENT"] !== "") { $arFields["COMMENTS"] = $arOrder["COMMENT"]; } if ($contactId != null && intval($contactId) > 0) { $arFields["CONTACT_ID"] = $contactId; } if ($companyId != null && intval($companyId) > 0) { $arFields["COMPANY_ID"] = $companyId; } static $arStageList = null; if ($arStageList == null) { $arStageList = CCrmStatus::GetStatusList('DEAL_STAGE'); } // Prevent reset stage for existed deals if ($newDeal && array_key_exists("NEW", $arStageList)) { $arFields["STAGE_ID"] = "NEW"; } $arAdditionalInfo = array(); if ($contactId != null && intval($contactId) > 0) { if (isset($arOrder["CONTRACTOR"]["FULL_NAME"]) && $arOrder["CONTRACTOR"]["FULL_NAME"] != "") { $arAdditionalInfo['CONTACT_FULL_NAME'] = $arOrder["CONTRACTOR"]["FULL_NAME"]; } elseif (isset($arOrder["CONTRACTOR"]["NAME"]) && $arOrder["CONTRACTOR"]["NAME"] != "") { $arAdditionalInfo['CONTACT_FULL_NAME'] = $arOrder["CONTRACTOR"]["NAME"]; } } if ($companyId != null && intval($companyId) > 0) { if (isset($arOrder["CONTRACTOR"]["OFFICIAL_NAME"]) && $arOrder["CONTRACTOR"]["OFFICIAL_NAME"] != "") { $arAdditionalInfo['COMPANY_FULL_NAME'] = $arOrder["CONTRACTOR"]["OFFICIAL_NAME"]; } elseif (isset($arOrder["CONTRACTOR"]["NAME"]) && $arOrder["CONTRACTOR"]["NAME"] != "") { $arAdditionalInfo['COMPANY_FULL_NAME'] = $arOrder["CONTRACTOR"]["NAME"]; } } if (is_array($arOrder["PROPERTIES"])) { foreach ($arOrder["PROPERTIES"] as $arProp) { if (!empty($arProp["VALUE"])) { $arAdditionalInfo[strtoupper($arProp["NAME"])] = $arProp["VALUE"]; if ($arAdditionalInfo[strtoupper($arProp["NAME"])] == "true") { $arAdditionalInfo[strtoupper($arProp["NAME"])] = true; } elseif ($arAdditionalInfo[strtoupper($arProp["NAME"])] == "false") { $arAdditionalInfo[strtoupper($arProp["NAME"])] = false; } } switch (strtoupper($arProp["NAME"])) { case 'FINALSTATUS': if ($arProp["VALUE"] == 'true') { $arFields["CLOSED"] = "Y"; //$arFields["CLOSEDATE"] = $arOrder["DATE_UPDATE"]; } else { $arFields["CLOSED"] = "N"; //$arFields["CLOSEDATE"] = false; } break; case 'CANCELED': if ($arProp["VALUE"] == 'true') { if (array_key_exists("LOSE", $arStageList)) { $arFields["STAGE_ID"] = "LOSE"; } $arFields["PROBABILITY"] = 0; } break; case 'ORDERPAID': if ($arProp["VALUE"] == 'true') { if (array_key_exists("WON", $arStageList)) { $arFields["STAGE_ID"] = "WON"; } $arFields["PROBABILITY"] = 100; } break; case 'ORDERSTATUS': //$arFields["CLOSED"] = "Y"; //$arFields["CLOSEDATE"] = $arOrder["DATE_UPDATE"]; break; } } } $arFields["ADDITIONAL_INFO"] = serialize($arAdditionalInfo); $accountNumber = isset($arOrder["ACCOUNT_NUMBER"]) && $arOrder["ACCOUNT_NUMBER"] !== '' ? $arOrder["ACCOUNT_NUMBER"] : $arOrder["ID"]; $obj = new CCrmDeal(false); if ($dealId == 0) { $arFields['TITLE'] = sprintf("%s #%s", $this->arExternalSale["PREFIX"], $accountNumber); $arFields['OPENED'] = $this->arExternalSale["PUBLIC"]; $arFields["TYPE_ID"] = 'SALE'; $arFields["CLOSEDATE"] = ConvertTimeStamp(time() + CTimeZone::GetOffset() + 86400, "FULL"); if (!isset($arFields["PROBABILITY"])) { $arFields["PROBABILITY"] = $this->arExternalSale["PROBABILITY"]; } $assignedById = $this->arExternalSale["RESPONSIBLE"]; if ($assignedById > 0) { $arFields["ASSIGNED_BY_ID"] = $assignedById; } $res = $obj->Add($arFields, true, array('DISABLE_USER_FIELD_CHECK' => true)); if ($res > 0) { $dealId = (int) $res; $this->arImportResult->numberOfCreatedDeals++; } } else { if ($dealTitle === 'Deal') { $arFields['TITLE'] = sprintf("%s #%s", $this->arExternalSale["PREFIX"], $accountNumber); } // Disable properties change events generation ($bCompare = false) and user fields check 'DISABLE_USER_FIELD_CHECK' = true. $res = $obj->Update($dealId, $arFields, false, true, array('DISABLE_USER_FIELD_CHECK' => true)); if ($res) { $this->arImportResult->numberOfUpdatedDeals++; } } if (!$res) { if (($ex = $GLOBALS["APPLICATION"]->GetException()) !== false) { $this->AddError($ex->GetID(), $ex->GetString()); } else { $this->AddError("CDA", "Deal creation error"); } if (!empty($obj->LAST_ERROR)) { $this->AddError("CDA", $obj->LAST_ERROR); } return false; } return array($dealId, $newDeal); }
} } if (($arBizProcParametersValues = $CCrmBizProc->CheckFields($bEdit ? $arResult['ELEMENT']['ID'] : false, false, $arResult['ELEMENT']['ASSIGNED_BY'], $bEdit ? array($arResult['ELEMENT']['ID'] => $arEntityAttr[$arResult['ELEMENT']['ID']]) : null)) === false) { $arResult['ERROR_MESSAGE'] .= $CCrmBizProc->LAST_ERROR; } if (empty($arResult['ERROR_MESSAGE'])) { $DB->StartTransaction(); $bSuccess = false; if ($bEdit) { $bSuccess = $CCrmDeal->Update($arResult['ELEMENT']['ID'], $arFields, true, true, array('REGISTER_SONET_EVENT' => true)); } else { if ($originatorId > 0 && $originId > 0) { $arFields['ORIGINATOR_ID'] = $originatorId; $arFields['ORIGIN_ID'] = $originId; } $ID = $CCrmDeal->Add($arFields, true, array('REGISTER_SONET_EVENT' => true)); $bSuccess = $ID !== false; if ($bSuccess) { $arResult['ELEMENT']['ID'] = $ID; } } if ($bSuccess) { // Save settings if (is_array($productRowSettings) && count($productRowSettings) > 0) { $arSettings = CCrmProductRow::LoadSettings('D', $arResult['ELEMENT']['ID']); foreach ($productRowSettings as $k => $v) { $arSettings[$k] = $v; } CCrmProductRow::SaveSettings('D', $arResult['ELEMENT']['ID'], $arSettings); } unset($arSettings);
public static function CreateCrmDeal($title, $summa = 0, $nds = 0, $company_id, $contact_id, $user_id, $comments = '', $arFiles) { /* error_log("test\n",3,'konvita2.txt'); //define("LOG_FILENAME", $_SERVER["DOCUMENT_ROOT"]."/konvita.txt"); //AddMessage2Log("Create deal"); */ $arDeal = CArkaCrm::PrepareDealArray($title, $summa, $nds, $company_id, $contact_id, $user_id, $comments, $arFiles); /* //deb foreach($arDeal as $kk => $vv) { error_log("$kk === $vv\n",3,"konvita2.txt"); } */ //debug //AddMessage2Log(serialize($arDeal)); $deal = new CCrmDeal(); $id = $deal->Add($arDeal); return $id; }
public function executePhase() { if ($this->currentPhase === LeadConversionPhase::COMPANY_CREATION || $this->currentPhase === LeadConversionPhase::CONTACT_CREATION || $this->currentPhase === LeadConversionPhase::DEAL_CREATION) { if ($this->currentPhase === LeadConversionPhase::COMPANY_CREATION) { $entityTypeID = \CCrmOwnerType::Company; } elseif ($this->currentPhase === LeadConversionPhase::CONTACT_CREATION) { $entityTypeID = \CCrmOwnerType::Contact; } else { $entityTypeID = \CCrmOwnerType::Deal; } $entityTypeName = \CCrmOwnerType::ResolveName($entityTypeID); $config = $this->config->getItem($entityTypeID); if (!$config->isActive()) { return false; } /** @var \CCrmPerms $permissions */ $permissions = $this->getUserPermissions(); $entityID = isset($this->contextData[$entityTypeName]) ? $this->contextData[$entityTypeName] : 0; if ($entityID > 0) { if ($entityTypeID === \CCrmOwnerType::Company) { if (!\CCrmCompany::Exists($entityID)) { throw new EntityConversionException(\CCrmOwnerType::Lead, \CCrmOwnerType::Company, EntityConversionException::TARG_DST, EntityConversionException::NOT_FOUND); } $entity = new \CCrmCompany(false); } elseif ($entityTypeID === \CCrmOwnerType::Contact) { if (!\CCrmContact::Exists($entityID)) { throw new EntityConversionException(\CCrmOwnerType::Lead, \CCrmOwnerType::Contact, EntityConversionException::TARG_DST, EntityConversionException::NOT_FOUND); } $entity = new \CCrmContact(false); } else { if (!\CCrmDeal::Exists($entityID)) { throw new EntityConversionException(\CCrmOwnerType::Lead, \CCrmOwnerType::Deal, EntityConversionException::TARG_DST, EntityConversionException::NOT_FOUND); } $entity = new \CCrmDeal(false); } if (!\CCrmAuthorizationHelper::CheckUpdatePermission($entityTypeName, $entityID, $permissions)) { throw new EntityConversionException(\CCrmOwnerType::Lead, $entityTypeID, EntityConversionException::TARG_DST, EntityConversionException::UPDATE_DENIED); } $fields = array('LEAD_ID' => $this->entityID); $entity->Update($entityID, $fields); $this->resultData[$entityTypeName] = $entityID; return true; } if (!\CCrmAuthorizationHelper::CheckCreatePermission($entityTypeName, $permissions)) { throw new EntityConversionException(\CCrmOwnerType::Lead, $entityTypeID, EntityConversionException::TARG_DST, EntityConversionException::CREATE_DENIED); } if (UserFieldSynchronizer::needForSynchronization(\CCrmOwnerType::Lead, $entityTypeID)) { throw new EntityConversionException(\CCrmOwnerType::Lead, $entityTypeID, EntityConversionException::TARG_DST, EntityConversionException::NOT_SYNCHRONIZED); } if (!ConversionSettings::getCurrent()->isAutocreationEnabled()) { throw new EntityConversionException(\CCrmOwnerType::Lead, $entityTypeID, EntityConversionException::TARG_DST, EntityConversionException::AUTOCREATION_DISABLED); } if (\CCrmBizProcHelper::HasAutoWorkflows($entityTypeID, \CCrmBizProcEventType::Create)) { throw new EntityConversionException(\CCrmOwnerType::Lead, $entityTypeID, EntityConversionException::TARG_DST, EntityConversionException::HAS_WORKFLOWS); } /** @var LeadConversionMapper $mapper */ $mapper = $this->getMapper(); $map = self::prepareMap($entityTypeID); $fields = $mapper->map($map); if (empty($fields)) { throw new EntityConversionException(\CCrmOwnerType::Lead, $entityTypeID, EntityConversionException::TARG_DST, EntityConversionException::EMPTY_FIELDS); } if ($entityTypeID === \CCrmOwnerType::Company) { $entity = new \CCrmCompany(false); $entityID = $entity->Add($fields); if ($entityID <= 0) { throw new EntityConversionException(\CCrmOwnerType::Lead, \CCrmOwnerType::Company, EntityConversionException::TARG_DST, EntityConversionException::CREATE_FAILED, $entity->LAST_ERROR); } //region BizProcess $arErrors = array(); \CCrmBizProcHelper::AutoStartWorkflows(\CCrmOwnerType::Company, $entityID, \CCrmBizProcEventType::Create, $arErrors); //endregion $this->resultData[\CCrmOwnerType::CompanyName] = $entityID; } elseif ($entityTypeID === \CCrmOwnerType::Contact) { if (isset($this->resultData[\CCrmOwnerType::CompanyName])) { $fields['COMPANY_ID'] = $this->resultData[\CCrmOwnerType::CompanyName]; } $entity = new \CCrmContact(false); if (!$entity->CheckFields($fields)) { throw new EntityConversionException(\CCrmOwnerType::Lead, $entityTypeID, EntityConversionException::TARG_DST, EntityConversionException::INVALID_FIELDS, $entity->LAST_ERROR); } $entityID = $entity->Add($fields); if ($entityID <= 0) { throw new EntityConversionException(\CCrmOwnerType::Lead, \CCrmOwnerType::Contact, EntityConversionException::TARG_DST, EntityConversionException::CREATE_FAILED, $entity->LAST_ERROR); } //region BizProcess $arErrors = array(); \CCrmBizProcHelper::AutoStartWorkflows(\CCrmOwnerType::Contact, $entityID, \CCrmBizProcEventType::Create, $arErrors); //endregion $this->resultData[\CCrmOwnerType::ContactName] = $entityID; } else { if (isset($this->resultData[\CCrmOwnerType::ContactName])) { $fields['CONTACT_ID'] = $this->resultData[\CCrmOwnerType::ContactName]; } if (isset($this->resultData[\CCrmOwnerType::CompanyName])) { $fields['COMPANY_ID'] = $this->resultData[\CCrmOwnerType::CompanyName]; } $productRows = isset($fields['PRODUCT_ROWS']) && is_array($fields['PRODUCT_ROWS']) ? $fields['PRODUCT_ROWS'] : array(); if (!empty($productRows)) { $result = \CCrmProductRow::CalculateTotalInfo('D', 0, false, $fields, $productRows); $fields['OPPORTUNITY'] = isset($result['OPPORTUNITY']) ? $result['OPPORTUNITY'] : 1.0; $fields['TAX_VALUE'] = isset($result['TAX_VALUE']) ? $result['TAX_VALUE'] : 0.0; } $entity = new \CCrmDeal(false); $entityID = $entity->Add($fields); if ($entityID <= 0) { throw new EntityConversionException(\CCrmOwnerType::Lead, \CCrmOwnerType::Deal, EntityConversionException::TARG_DST, EntityConversionException::CREATE_FAILED, $entity->LAST_ERROR); } if (!empty($productRows)) { \CCrmDeal::SaveProductRows($entityID, $productRows, false, false, false); } //region BizProcess $arErrors = array(); \CCrmBizProcHelper::AutoStartWorkflows(\CCrmOwnerType::Deal, $entityID, \CCrmBizProcEventType::Create, $arErrors); //endregion $this->resultData[\CCrmOwnerType::DealName] = $entityID; } return true; } elseif ($this->currentPhase === LeadConversionPhase::FINALIZATION) { $result = \CCrmLead::GetListEx(array(), array('=ID' => $this->entityID, 'CHECK_PERMISSIONS' => 'N'), false, false, array('STATUS_ID')); $presentFields = is_object($result) ? $result->Fetch() : null; if (is_array($presentFields)) { $fields = array(); $statusID = isset($presentFields['STATUS_ID']) ? $presentFields['STATUS_ID'] : ''; if ($statusID !== 'CONVERTED') { $fields['STATUS_ID'] = 'CONVERTED'; } if (isset($this->resultData[\CCrmOwnerType::CompanyName])) { $fields['COMPANY_ID'] = $this->resultData[\CCrmOwnerType::CompanyName]; } if (isset($this->resultData[\CCrmOwnerType::ContactName])) { $fields['CONTACT_ID'] = $this->resultData[\CCrmOwnerType::ContactName]; } if (!empty($fields)) { $entity = new \CCrmLead(false); if ($entity->Update($this->entityID, $fields)) { //region BizProcess $arErrors = array(); \CCrmBizProcHelper::AutoStartWorkflows(\CCrmOwnerType::Lead, $this->entityID, \CCrmBizProcEventType::Edit, $arErrors); //endregion } } } return true; } return false; }
public static function CreateDocument($parentDocumentId, $arFields) { global $DB; $arDocumentID = self::GetDocumentInfo($parentDocumentId); if ($arDocumentID == false) { $arDocumentID['TYPE'] = $parentDocumentId; } $arDocumentFields = self::GetDocumentFields($arDocumentID['TYPE']); $arKeys = array_keys($arFields); foreach ($arKeys as $key) { if (!array_key_exists($key, $arDocumentFields)) { //Fix for issue #40374 unset($arFields[$key]); continue; } $arFields[$key] = is_array($arFields[$key]) && !CBPHelper::IsAssociativeArray($arFields[$key]) ? $arFields[$key] : array($arFields[$key]); if ($arDocumentFields[$key]["Type"] == "user") { $ar = array(); foreach ($arFields[$key] as $v1) { if (substr($v1, 0, strlen("user_")) == "user_") { $ar[] = substr($v1, strlen("user_")); } else { $a1 = self::GetUsersFromUserGroup($v1, "DEAL_0"); foreach ($a1 as $a11) { $ar[] = $a11; } } } $arFields[$key] = $ar; } elseif ($arDocumentFields[$key]["Type"] == "select" && substr($key, 0, 3) == "UF_") { self::InternalizeEnumerationField('CRM_DEAL', $arFields, $key); } elseif ($arDocumentFields[$key]["Type"] == "file") { $arFileOptions = array('ENABLE_ID' => true); foreach ($arFields[$key] as &$value) { //Issue #40380. Secure URLs and file IDs are allowed. $file = false; CCrmFileProxy::TryResolveFile($value, $file, $arFileOptions); $value = $file; } unset($value); } elseif ($arDocumentFields[$key]["Type"] == "S:HTML") { foreach ($arFields[$key] as &$value) { $value = array("VALUE" => $value); } unset($value); } if (!$arDocumentFields[$key]["Multiple"] && is_array($arFields[$key])) { if (count($arFields[$key]) > 0) { $a = array_values($arFields[$key]); $arFields[$key] = $a[0]; } else { $arFields[$key] = null; } } } if (isset($arFields['COMMENTS'])) { if (preg_match('/<[^>]+[\\/]?>/i', $arFields['COMMENTS']) === 1) { $arFields['COMMENTS'] = htmlspecialcharsbx($arFields['COMMENTS']); } $arFields['COMMENTS'] = str_replace(array("\r\n", "\r", "\n"), "<br>", $arFields['COMMENTS']); } $DB->StartTransaction(); $CCrmEntity = new CCrmDeal(false); $id = $CCrmEntity->Add($arFields); if (!$id || $id <= 0) { $DB->Rollback(); throw new Exception($CCrmEntity->LAST_ERROR); } if (COption::GetOptionString("crm", "start_bp_within_bp", "N") == "Y") { $CCrmBizProc = new CCrmBizProc('DEAL'); if (false === $CCrmBizProc->CheckFields(false, true)) { throw new Exception($CCrmBizProc->LAST_ERROR); } if ($id && $id > 0 && !$CCrmBizProc->StartWorkflow($id)) { $DB->Rollback(); throw new Exception($CCrmBizProc->LAST_ERROR); $id = false; } } if ($id && $id > 0) { $DB->Commit(); } return $id; }
public function createDeals(array $params) { $date = isset($params['DATE']) ? $params['DATE'] : null; if (!$date) { $date = $date = new Date(); } $dateFormat = Date::convertFormatToPhp(FORMAT_DATE); $count = isset($params['COUNT']) ? (int) $params['COUNT'] : 0; if ($count <= 0) { return; } $duration = isset($params['DURATION']) ? (int) $params['DURATION'] : 0; if ($duration <= 0) { $duration = 7; } $probability = isset($params['PROBABILITY']) ? (int) $params['PROBABILITY'] : 0; if ($probability <= 0) { $probability = 10; } $typeID = isset($params['TYPE_ID']) ? $params['TYPE_ID'] : ''; if ($typeID === '') { $typeID = 'SALE'; } $prefix = isset($params['PREFIX']) ? $params['PREFIX'] : ''; if ($prefix === '') { $prefix = $this->id; } $stageIDs = isset($params['STAGE_IDS']) && is_array($params['STAGE_IDS']) ? $params['STAGE_IDS'] : array(); if (empty($stageIDs)) { $stageIDs[] = 'NEW'; } $stageCount = count($stageIDs); $userIDs = isset($params['USER_IDS']) && is_array($params['USER_IDS']) ? $params['USER_IDS'] : array(); if (empty($userIDs)) { $userIDs[] = \CCrmSecurityHelper::GetCurrentUserID(); } $currencyID = isset($params['CURRENCY_ID']) ? $params['CURRENCY_ID'] : ''; if ($currencyID === '') { $currencyID = \CCrmCurrency::GetBaseCurrencyID(); } $minSum = isset($params['MIN_SUM']) ? (int) $params['MIN_SUM'] : 0; if ($minSum <= 0) { $minSum = 100; } $maxSum = isset($params['MAX_SUM']) ? (int) $params['MAX_SUM'] : 0; if ($maxSum <= 0) { $maxSum = 1000; } $clientInfos = isset($params['CLIENT_INFOS']) && is_array($params['CLIENT_INFOS']) ? $params['CLIENT_INFOS'] : array(); $callCount = isset($params['CALL_COUNT']) ? (int) $params['CALL_COUNT'] : 0; $meetingCount = isset($params['MEETING_COUNT']) ? (int) $params['MEETING_COUNT'] : 0; $invoiceCount = isset($params['INVOICE_COUNT']) ? (int) $params['INVOICE_COUNT'] : 0; $number = isset($params['NUMBER']) ? (int) $params['NUMBER'] : 0; if ($number <= 0) { $number = 0; } $dealEntity = new \CCrmDeal(false); for ($i = 0; $i < $count; $i++) { $number++; $title = "{$prefix} deal # {$number}"; $beginDate = clone $date; $opportunity = mt_rand($minSum, $maxSum); $fields = array('TITLE' => $title, 'TYPE_ID' => $typeID, 'STAGE_ID' => $stageIDs[0], 'PROBABILITY' => $probability, 'CURRENCY_ID' => $currencyID, 'OPPORTUNITY' => $opportunity, 'ASSIGNED_BY_ID' => self::getRandomItem($userIDs), 'BEGINDATE' => $beginDate->format($dateFormat), 'CLOSEDATE' => $beginDate->add("{$duration} days")->format($dateFormat), 'ORIGINATOR_ID' => $this->id); $contactID = 0; $companyID = 0; $clientInfo = self::getRandomItem($clientInfos); if (is_array($clientInfo)) { if (isset($clientInfo['CONTACT_ID'])) { $contactID = $clientInfo['CONTACT_ID']; } if (isset($clientInfo['COMPANY_ID'])) { $companyID = $clientInfo['COMPANY_ID']; } } if ($contactID > 0) { $fields['CONTACT_ID'] = $contactID; } if ($companyID > 0) { $fields['COMPANY_ID'] = $companyID; } $ID = $dealEntity->Add($fields, true, array('ENABLE_CLOSE_DATE_SYNC' => false)); $lastStage = $stageIDs[$stageCount - 1]; if ($stageCount > 1) { $lastStageIndex = mt_rand(1, $stageCount - 1); $lastStage = $stageIDs[$lastStageIndex]; for ($j = 1; $j <= $lastStageIndex; $j++) { $fields = array('STAGE_ID' => $stageIDs[$j]); $dealEntity->Update($ID, $fields, true, true, array('ENABLE_CLOSE_DATE_SYNC' => false)); } } $clientTypeID = \CCrmOwnerType::Undefined; $clientID = 0; if ($contactID > 0) { $clientTypeID = \CCrmOwnerType::Contact; $clientID = $contactID; } elseif ($companyID > 0) { $clientTypeID = \CCrmOwnerType::Company; $clientID = $companyID; } if ($clientID > 0) { if ($callCount > 0) { $this->createActivities(array('COUNT' => $callCount, 'OWNER_TYPE_ID' => \CCrmOwnerType::Deal, 'OWNER_ID' => $ID, 'SUBJECT_PREFIX' => "Call for {$title}", 'DATE' => $date, 'MAX_DATE_OFFSET' => $duration, 'CLIENT_TYPE_ID' => $clientTypeID, 'CLIENT_ID' => $clientID, 'TYPE_ID' => \CCrmActivityType::Call, 'USER_IDS' => $userIDs)); } if ($meetingCount > 0) { $this->createActivities(array('COUNT' => $meetingCount, 'OWNER_TYPE_ID' => \CCrmOwnerType::Deal, 'OWNER_ID' => $ID, 'SUBJECT_PREFIX' => "Meeting for {$title}", 'DATE' => $date, 'MAX_DATE_OFFSET' => $duration, 'CLIENT_TYPE_ID' => $clientTypeID, 'CLIENT_ID' => $clientID, 'TYPE_ID' => \CCrmActivityType::Meeting, 'USER_IDS' => $userIDs)); } } if ($invoiceCount > 0) { $this->createInvoices(array('COUNT' => $invoiceCount, 'SUM' => $opportunity, 'DEAL_ID' => $ID, 'CONTACT_ID' => $contactID, 'COMPANY_ID' => $companyID, 'USER_IDS' => $userIDs, 'PREFIX' => $prefix, 'DATE' => $date, 'MAX_DATE_OFFSET' => $duration, 'IS_WON' => $lastStage === 'WON')); } } }
public function executePhase() { if ($this->currentPhase === QuoteConversionPhase::DEAL_CREATION || $this->currentPhase === QuoteConversionPhase::INVOICE_CREATION) { if ($this->currentPhase === QuoteConversionPhase::DEAL_CREATION) { $entityTypeID = \CCrmOwnerType::Deal; } else { $entityTypeID = \CCrmOwnerType::Invoice; } $entityTypeName = \CCrmOwnerType::ResolveName($entityTypeID); $config = $this->config->getItem($entityTypeID); if (!$config->isActive()) { return false; } /** @var \CCrmPerms $permissions */ $permissions = $this->getUserPermissions(); $entityID = isset($this->contextData[$entityTypeName]) ? $this->contextData[$entityTypeName] : 0; if ($entityID > 0) { if ($entityTypeID === \CCrmOwnerType::Deal) { if (!\CCrmDeal::Exists($entityID)) { throw new EntityConversionException(\CCrmOwnerType::Quote, \CCrmOwnerType::Deal, EntityConversionException::TARG_DST, EntityConversionException::NOT_FOUND); } $this->resultData[$entityTypeName] = $entityID; } else { if (!\CCrmInvoice::Exists($entityID)) { throw new EntityConversionException(\CCrmOwnerType::Quote, \CCrmOwnerType::Invoice, EntityConversionException::TARG_DST, EntityConversionException::NOT_FOUND); } if (!\CCrmInvoice::CheckUpdatePermission($entityID, $permissions)) { throw new EntityConversionException(\CCrmOwnerType::Quote, \CCrmOwnerType::Invoice, EntityConversionException::TARG_DST, EntityConversionException::UPDATE_DENIED); } $entity = new \CCrmInvoice(false); $fields = array('UF_QUOTE_ID' => $this->entityID); try { $entity->Update($entityID, $fields); } catch (Main\DB\SqlQueryException $e) { } $this->resultData[$entityTypeName] = $entityID; } return true; } if (!\CCrmAuthorizationHelper::CheckCreatePermission($entityTypeName, $permissions)) { throw new EntityConversionException(\CCrmOwnerType::Quote, $entityTypeID, EntityConversionException::TARG_DST, EntityConversionException::CREATE_DENIED); } if (UserFieldSynchronizer::needForSynchronization(\CCrmOwnerType::Quote, $entityTypeID)) { throw new EntityConversionException(\CCrmOwnerType::Quote, $entityTypeID, EntityConversionException::TARG_DST, EntityConversionException::NOT_SYNCHRONIZED); } if (!ConversionSettings::getCurrent()->isAutocreationEnabled()) { throw new EntityConversionException(\CCrmOwnerType::Quote, $entityTypeID, EntityConversionException::TARG_DST, EntityConversionException::AUTOCREATION_DISABLED); } if ($entityTypeID === \CCrmOwnerType::Deal && \CCrmBizProcHelper::HasAutoWorkflows($entityTypeID, \CCrmBizProcEventType::Create)) { throw new EntityConversionException(\CCrmOwnerType::Lead, $entityTypeID, EntityConversionException::TARG_DST, EntityConversionException::HAS_WORKFLOWS); } /** @var QuoteConversionMapper $mapper */ $mapper = $this->getMapper(); $map = self::prepareMap($entityTypeID); $fields = $mapper->map($map); if (empty($fields)) { throw new EntityConversionException(\CCrmOwnerType::Quote, $entityTypeID, EntityConversionException::TARG_DST, EntityConversionException::EMPTY_FIELDS); } if ($entityTypeID === \CCrmOwnerType::Deal) { $entity = new \CCrmDeal(false); if (!$entity->CheckFields($fields)) { throw new EntityConversionException(\CCrmOwnerType::Quote, \CCrmOwnerType::Deal, EntityConversionException::TARG_DST, EntityConversionException::INVALID_FIELDS, $entity->LAST_ERROR); } $productRows = isset($fields['PRODUCT_ROWS']) && is_array($fields['PRODUCT_ROWS']) ? $fields['PRODUCT_ROWS'] : array(); if (!empty($productRows)) { $result = \CCrmProductRow::CalculateTotalInfo('D', 0, false, $fields, $productRows); $fields['OPPORTUNITY'] = isset($result['OPPORTUNITY']) ? $result['OPPORTUNITY'] : 1.0; $fields['TAX_VALUE'] = isset($result['TAX_VALUE']) ? $result['TAX_VALUE'] : 0.0; } $entityID = $entity->Add($fields); if ($entityID <= 0) { throw new EntityConversionException(\CCrmOwnerType::Quote, \CCrmOwnerType::Deal, EntityConversionException::TARG_DST, EntityConversionException::CREATE_FAILED, $entity->LAST_ERROR); } if (!empty($productRows)) { \CCrmDeal::SaveProductRows($entityID, $productRows, false, false, false); } $this->resultData[\CCrmOwnerType::DealName] = $entityID; } else { $entity = new \CCrmInvoice(false); if (!$entity->CheckFields($fields)) { throw new EntityConversionException(\CCrmOwnerType::Quote, \CCrmOwnerType::Invoice, EntityConversionException::TARG_DST, EntityConversionException::INVALID_FIELDS, $entity->LAST_ERROR); } $entityID = $entity->Add($fields); if ($entityID <= 0) { throw new EntityConversionException(\CCrmOwnerType::Quote, \CCrmOwnerType::Invoice, EntityConversionException::TARG_DST, EntityConversionException::CREATE_FAILED, $entity->LAST_ERROR); } $this->resultData[\CCrmOwnerType::InvoiceName] = $entityID; } return true; } elseif ($this->currentPhase === DealConversionPhase::FINALIZATION) { $fields = array(); if (isset($this->resultData[\CCrmOwnerType::DealName])) { $fields['DEAL_ID'] = $this->resultData[\CCrmOwnerType::DealName]; } if (!empty($fields)) { $entity = new \CCrmQuote(false); $entity->Update($this->entityID, $fields); } return true; } return false; }
} else { $dealID = uniqid(); } // For compatibility only. Try sync product PRICE if (isset($arDeal['PRODUCT_ROWS']) && count($arDeal['PRODUCT_ROWS']) == 1 && !isset($arDeal['PRODUCT_ROWS'][0]['PRICE']) && isset($arDeal['OPPORTUNITY'])) { $arDeal['PRODUCT_ROWS'][0]['PRICE'] = doubleval($arDeal['OPPORTUNITY']); } if ($canBreak && count($arDeals) >= 20) { break; } $arDeals[$dealID] = $arDeal; $filePos = $csvFile->GetPos(); } foreach ($arDeals as $arDeal) { $arDeal['PERMISSION'] = 'IMPORT'; if (!$CCrmDeal->Add($arDeal)) { $arResult['error']++; $arResult['error_data'][] = array('message' => $arDeal['RESULT_MESSAGE'], 'data' => $arDeal['__CSV_DATA__']); } else { if (!empty($arDeal)) { if (isset($arDeal['PRODUCT_ROWS']) && count($arDeal['PRODUCT_ROWS']) > 0) { if (!CCrmDeal::SaveProductRows($arDeal['ID'], $arDeal['PRODUCT_ROWS'])) { $arResult['error']++; $arResult['error_data'][] = array('message' => CCrmProductRow::GetLastError(), 'data' => $arDeal['__CSV_DATA__']); } } $arResult['import']++; } } } $_SESSION['CRM_IMPORT_FILE_POS'] = $filePos;