34 $this->order = $order;
44 $contactCompanyCollection = $this->order->getContactCompanyCollection();
45 if ($contactCompanyCollection && $contactCompanyCollection->isEmpty())
47 $this->addContactCompany();
50 $this->setContactCompanyRequisites();
52 if (!$this->isSetResponsible())
54 $this->setResponsible();
57 $saveOrderResult = $this->order->save();
58 if ($saveOrderResult->isSuccess())
60 $this->addTimeLines();
64 $result->addErrors($saveOrderResult->getErrors());
73 private function isSetResponsible(): bool
75 return (
bool)$this->order->getField(
"RESPONSIBLE_ID");
78 private function setResponsible(): void
80 $this->order->setFieldNoDemand(
82 Settings\OrderSettings::getCurrent()->getDefaultResponsibleId()
89 private function addContactCompany(): void
91 $matches = Matcher\EntityMatchManager::getInstance()->match($this->order);
95 $communication = $this->order->getContactCompanyCollection();
96 if (isset($matches[\CCrmOwnerType::Contact]))
99 $contact = Order\Contact::create($communication);
100 $contact->setField(
"ENTITY_ID", $matches[\CCrmOwnerType::Contact]);
101 $contact->setField(
"IS_PRIMARY",
"Y");
103 $communication->addItem($contact);
106 if (isset($matches[\CCrmOwnerType::Company]))
109 $company = Order\Company::create($communication);
110 $company->setField(
"ENTITY_ID", $matches[\CCrmOwnerType::Company]);
111 $company->setField(
"IS_PRIMARY",
"Y");
113 $communication->addItem($company);
121 private function setContactCompanyRequisites(): void
123 $collection = $this->order->getContactCompanyCollection();
129 $entity = $collection->getPrimaryCompany();
130 if ($entity ===
null)
132 $entity = $collection->getPrimaryContact();
135 if ($entity ===
null)
141 "MC_REQUISITE_ID" => 0,
142 "MC_BANK_DETAIL_ID" => 0
145 $requisiteList = $entity->getRequisiteList();
148 $result[
"REQUISITE_ID"] = current($requisiteList)[
"ID"];
151 $bankRequisiteList = $entity->getBankRequisiteList();
152 if ($bankRequisiteList)
154 $result[
"BANK_DETAIL_ID"] = current($bankRequisiteList)[
"ID"];
157 $this->order->setRequisiteLink($result);
160 private function addTimeLines(): void
163 $this->addTimelineEntryOnCreate();
165 $historyChanges = $this->getHistoryChanges();
166 foreach ($historyChanges as $historyChange)
169 if ($historyChange[
"TYPE"] ===
"ORDER_STATUS_CHANGED")
171 $this->addTimelineEntryOnStatusModify($historyChange[
"DATA"][
"OLD"], $historyChange[
"DATA"][
"CURRENT"]);
176 $this->addTimelineEntryOnCancel();
182 private function addTimelineEntryOnCreate(): void
184 Timeline\OrderController::getInstance()->onCreate(
185 $this->order->getId(),
188 "ID" => (
int)$this->order->getId(),
189 "CREATED_BY" => $this->order->getField(
"CREATED_BY"),
190 "RESPONSIBLE_ID" => $this->order->getField(
"RESPONSIBLE_ID"),
191 "DATE_INSERT" => $this->order->getField(
"DATE_INSERT"),
192 "PRICE" => $this->order->getField(
"PRICE"),
193 "CURRENCY" => $this->order->getField(
"CURRENCY")
197 "ENTITY_TYPE_ID" => \CCrmOwnerType::Order,
198 "ENTITY_ID" => $this->order->getId()
208 private function addTimelineEntryOnCancel(): void
210 if ($this->order->getField(
"CANCELED") !==
"Y")
216 "ID" => $this->order->getId(),
217 "CANCELED" => $this->order->getField(
"CANCELED"),
220 $fields[
"REASON_CANCELED"] = $this->order->getField(
"REASON_CANCELED");
221 $fields[
"EMP_CANCELED_ID"] = $this->order->getField(
"EMP_CANCELED_ID");
223 Timeline\OrderController::getInstance()->onCancel(
224 $this->order->getId(),
229 "ENTITY_TYPE_ID" => \CCrmOwnerType::Order,
230 "ENTITY_ID" => $this->order->getId()
242 private function addTimelineEntryOnStatusModify($prevStatus, $currentStatus): void
245 "PREVIOUS_FIELDS" => [
"STATUS_ID" => $prevStatus],
246 "CURRENT_FIELDS" => [
247 "STATUS_ID" => $currentStatus,
248 "EMP_STATUS_ID" => $this->order->getField(
"EMP_STATUS_ID")
252 "ENTITY_TYPE_ID" => \CCrmOwnerType::Order,
253 "ENTITY_ID" => $this->order->getId()
258 Timeline\OrderController::getInstance()->onModify($this->order->getId(), $modifyParams);
264 private function getHistoryChanges(): array
268 $arFilterHistory = [
"ORDER_ID" => $this->order->getId()];
269 $arFilterHistory[
"@TYPE"] = [
"ORDER_STATUS_CHANGED"];
271 $dbOrderChange = Sale\Internals\OrderChangeTable::getList([
273 "filter" => $arFilterHistory,
275 "DATE_CREATE" =>
"DESC",
280 while ($arChangeRecord = $dbOrderChange->fetch())
282 $arHistoryData[] = $arChangeRecord;
285 Main\Type\Collection::sortByColumn($arHistoryData, [
'ID' => SORT_ASC]);
287 $dbRes = new \CDBResult();
288 $dbRes->InitFromArray($arHistoryData);
291 while ($arRes = $dbRes->Fetch())
293 if (\CheckSerializedData($arRes[
"DATA"]))
295 $data = unserialize($arRes[
"DATA"], [
'allowed_classes' =>
false]);
296 if ($arRes[
"TYPE"] ===
"ORDER_STATUS_CHANGED")
299 "TYPE" => $arRes[
"TYPE"],
301 "CURRENT" => $data[
"STATUS_ID"],
302 "OLD" => $data[
"OLD_STATUS_ID"],
355 private $orderList = [];
357 private $params = [];
365 if (!Main\Loader::includeModule(
"crm"))
372 $this->orderList = self::isUpdateOrder() ? $this->getErrorOrders() : $this->getOrders();
373 if (!$this->orderList)
380 if (self::getErrors()->fetch())
382 $this->addAdminErrorNotify(
Loc::getMessage(
"CRM_ENTITY_CREATOR_STEPPER_ERROR_NOTIFY"));
386 $this->addAdminNormalNotify(
396 $this->createCrmEntity();
399 "count" => self::isUpdateOrder() ? $this->getErrorOrderCount() : $this->getOrderCount(),
400 "steps" => $this->params[
"updated_order_count"],
406 private function createCrmEntity(): void
408 $timeStart = Main\Diag\Helper::getCurrentMicrotime();
409 foreach ($this->orderList as $order)
414 $resultAdd = $crmEntity->create();
415 if (!$resultAdd->isSuccess())
417 $errorMessages = $resultAdd->getErrorMessages();
418 $this->setError($order->getId(), implode(
" ", $errorMessages));
422 if (self::isUpdateOrder())
424 $this->deleteError($order->getId());
428 catch (\Exception $ex)
430 $this->setError($order->getId(), $ex->getMessage());
433 $this->updateParams($order->getId());
435 $timeEnd = Main\Diag\Helper::getCurrentMicrotime();
436 if ($timeEnd - $timeStart > self::MAX_EXECUTION_TIME)
443 private function initParams(): void
445 $params = Option::get(self::$moduleId, self::STEPPER_PARAMS,
"");
446 if ($params !==
"" && \CheckSerializedData($params))
448 $params = unserialize($params, [
'allowed_classes' =>
false]);
451 $this->params = (\is_array($params) ? $params : []);
452 if (empty($this->params))
455 "last_order_id" =>
null,
456 "updated_order_count" => 0
464 private function updateParams($orderId): void
466 $this->params[
"last_order_id"] = $orderId;
467 $this->params[
"updated_order_count"]++;
469 Option::set(self::$moduleId, self::STEPPER_PARAMS, serialize($this->params));
475 private function getOrders(): ?array
478 "order" => [
"ID" =>
"ASC"],
481 if ($this->params[
"last_order_id" ] !==
null)
483 $parameters[
"filter"] = [
">ID" => $this->params[
"last_order_id"]];
486 return Order\Order::loadByFilter($parameters);
489 private function getErrorOrders()
492 "order" => [
"ORDER_ID" =>
"ASC"],
495 if ($this->params[
"last_order_id" ] !==
null)
497 $parameters[
"filter"] = [
">ORDER_ID" => $this->params[
"last_order_id"]];
500 $errorOrderIdList = [];
502 while($orderError = $orderErrorIterator->fetch())
504 $errorOrderIdList[] = $orderError[
"ORDER_ID"];
507 if ($errorOrderIdList)
510 "filter" => [
"ID" => $errorOrderIdList]
513 $orders = Order\Order::loadByFilter($parameters);
515 foreach ($orders as $order)
517 $ordersIdList[] = $order->getId();
520 $diffOrderListId = array_diff($errorOrderIdList, $ordersIdList);
521 foreach ($diffOrderListId as $diffOrderId)
523 $this->deleteError($diffOrderId);
532 private function getOrderCount()
534 return Order\Order::getList([
537 new Main\Entity\ExpressionField(
"CNT",
"COUNT(*)")
542 private function getErrorOrderCount()
544 $optionValue = Option::get(self::$moduleId, self::ORDER_CONVERTER_CRM_ERROR_COUNT,
false);
545 if ($optionValue ===
false)
547 $optionValue = Sale\Internals\OrderConverterCrmErrorTable::getList([
550 new Main\Entity\ExpressionField(
"CNT",
"COUNT(*)")
554 Option::set(self::$moduleId, self::ORDER_CONVERTER_CRM_ERROR_COUNT, $optionValue);
562 Option::set(self::$moduleId, self::ORDER_CONVERT_IS_FINISH,
"Y");
570 return (Option::get(self::$moduleId, self::ORDER_CONVERT_IS_FINISH,
"N") ===
"Y");
576 private static function isUpdateOrder(): bool
578 return (Option::get(self::$moduleId, self::UPDATE_ORDER_CONVERTER_CRM_ERROR_TABLE,
"N") ===
"Y");
587 if (Option::get(
"sale", self::IS_CRM_SITE_MASTER_OPENED,
"N") ===
"Y")
591 Option::get(
"sale", self::IS_SALE_CRM_SITE_MASTER_STUB,
"N") ===
"Y"
592 && Option::get(
"sale", self::IS_SALE_CRM_SITE_MASTER_FINISH,
"N") ===
"Y"
600 $isShow = Main\ModuleManager::isModuleInstalled(
"crm");
606 if (Option::get(
'sale', self::PREFIX_OPTION_ADMIN_PANEL_IS_ENABLED.$USER->GetID()) !==
'Y')
620 return (
bool)\CAgent::GetList(
623 "NAME" => __CLASS__.
"::execAgent();"
633 if (defined(
"ADMIN_SECTION")
634 || (defined(
"SITE_TEMPLATE_ID") && SITE_TEMPLATE_ID !==
"bitrix24")
640 if (self::getCrmSiteId() !== SITE_ID)
647 $currentPage = $APPLICATION->getCurPage();
648 if ((mb_strpos($currentPage,
"/crm/") !==
false) || (mb_strpos($currentPage,
"/shop/") !==
false))
650 $ids = [
"sale" => __CLASS__];
654 $APPLICATION->AddViewContent(
"above_pagetitle", $content);
672 defined(
"ADMIN_SECTION")
673 || (defined(
"SITE_TEMPLATE_ID") && SITE_TEMPLATE_ID !==
"bitrix24")
674 || (!Main\Loader::includeModule(
"crm"))
680 if (self::getCrmSiteId() !== SITE_ID)
685 if (!\CAllCrmInvoice::installExternalEntities())
692 && !self::isFinished()
695 include_once $_SERVER[
"DOCUMENT_ROOT"].BX_ROOT.
"/components/bitrix/sale.crm.site.master/tools/sitepatcher.php";
696 $sitePatcher = \Bitrix\Sale\CrmSiteMaster\Tools\SitePatcher::getInstance();
697 $sitePatcher->setCrmUserGroups();
698 $sitePatcher->setCrmGroupRights();
701 \Bitrix\Sale\CrmSiteMaster\Tools\SitePatcher::deleteEmployeesGroupId();
702 \Bitrix\Sale\CrmSiteMaster\Tools\SitePatcher::deleteCompanyDepartmentId();
703 \Bitrix\Sale\CrmSiteMaster\Tools\SitePatcher::retrieveConfig1C();
715 RegisterModuleDependences(
"main",
"OnEpilog", self::$moduleId, __CLASS__,
"showProgressBar", 500);
716 RegisterModuleDependences(
"main",
"OnEpilog", self::$moduleId, __CLASS__,
"bindAgent", 500);
724 UnRegisterModuleDependences(
"main",
"OnEpilog", self::$moduleId, __CLASS__,
"showProgressBar");
725 UnRegisterModuleDependences(
"main",
"OnEpilog", self::$moduleId, __CLASS__,
"bindAgent");
730 if (!self::isAgent())
732 Option::delete(self::$moduleId, [
"name" => self::STEPPER_PARAMS]);
733 Option::delete(self::$moduleId, [
"name" => self::ORDER_CONVERT_IS_FINISH]);
735 Option::set(self::$moduleId, self::UPDATE_ORDER_CONVERTER_CRM_ERROR_TABLE,
"Y");
747 Option::delete(self::$moduleId, [
"name" => self::ORDER_CONVERT_IS_FINISH]);
748 Option::delete(self::$moduleId, [
"name" => self::ORDER_CONVERTER_CRM_ERROR_COUNT]);
750 RegisterModuleDependences(
"main",
"OnEpilog", self::$moduleId, __CLASS__,
"showProgressBar", 500);
751 RegisterModuleDependences(
"main",
"OnEpilog", self::$moduleId, __CLASS__,
"bindAgentOrderUpdate", 500);
759 UnRegisterModuleDependences(
"main",
"OnEpilog", self::$moduleId, __CLASS__,
"showProgressBar");
760 UnRegisterModuleDependences(
"main",
"OnEpilog", self::$moduleId, __CLASS__,
"bindAgentOrderUpdate");
767 private function setError($orderId, $errorMessage): void
769 $orderRow = Sale\Internals\OrderConverterCrmErrorTable::getList([
770 'filter' => [
"ORDER_ID" => $orderId],
774 $this->addError($orderId, $errorMessage);
778 $this->updateError($orderId, $errorMessage);
785 private function addError($orderId, $errorMessage): void
787 Sale\Internals\OrderConverterCrmErrorTable::add([
788 "ORDER_ID" => $orderId,
789 "ERROR" => $errorMessage
797 private function updateError($orderId, $errorMessage): void
799 Sale\Internals\OrderConverterCrmErrorTable::update($orderId, [
800 "ERROR" => $errorMessage
807 private function deleteError($orderId): void
809 $orderRow = Sale\Internals\OrderConverterCrmErrorTable::getList([
811 "filter" => [
"ORDER_ID" => $orderId],
815 Sale\Internals\OrderConverterCrmErrorTable::delete($orderRow[
"ID"]);
822 public static function getErrors(array $parameters = [])
824 return Sale\Internals\OrderConverterCrmErrorTable::getList($parameters);
830 private function addAdminNormalNotify($message): void
832 $this->addAdminNotify($message, \CAdminNotify::TYPE_NORMAL);
838 private function addAdminErrorNotify($message): void
840 $this->addAdminNotify($message, \CAdminNotify::TYPE_ERROR);
848 private function addAdminNotify($message, $notifyType): void
851 "MODULE_ID" =>
"sale",
852 "TAG" =>
"crm_entity_stepper",
853 "MESSAGE" => $message,
854 "NOTIFY_TYPE" => $notifyType,
855 "PUBLIC_SECTION" =>
"N",
862 private static function getCrmSiteId(): string
864 return Option::get(self::$moduleId, self::WIZARD_SITE_ID);
872 $site = Main\SiteTable::getList([
873 "select" => [
"SERVER_NAME"],
874 "filter" => [
"=LID" => self::getCrmSiteId()]
877 $siteUrl = (Main\Context::getCurrent()->getRequest()->isHttps() ?
"https://" :
"http://").$site[
"SERVER_NAME"];
878 $pathToOderList = Option::get(
"crm",
"path_to_order_list",
"/shop/orders/");
880 return $siteUrl.$pathToOderList;
888 $value = Option::get(
'sale', self::PREFIX_OPTION_ADMIN_PANEL_IS_ENABLED.$params[
'USER_ID'],
'');
889 if ($value !==
'' && $value !==
'N')
891 Option::set(
'sale', self::PREFIX_OPTION_ADMIN_PANEL_IS_ENABLED.$params[
'USER_ID'],
'N');
static getMessage($code, $replace=null, $language=null)
static getHtml($ids=array(), $title="")