Ejemplo n.º 1
0
        if (isset($optionsLegalDetails[$code])) {
            $optionsOrderProps[$code] = array_merge($optionsOrderProps[$code], $optionsLegalDetails[$code]);
        }
        if (isset($optionsCustomFields[$code])) {
            $optionsOrderProps[$code] = array_merge($optionsOrderProps[$code], $optionsCustomFields[$code]);
        }
        $optionsOrderProps[$code]['location'] = 'LOCATION';
        if (array_search('CITY', $optionsOrderProps[$code]) == false) {
            $optionsOrderProps[$code]['city'] = 'CITY';
        }
        if (array_search('ZIP', $optionsOrderProps[$code]) == false) {
            $optionsOrderProps[$code]['index'] = 'ZIP';
        }
    }
    
    $api = new RetailCrm\RestApi($api_host, $api_key);
    
    $order = $api->orderGet($idOrderCRM, $by = 'id');
    
    $log = new Logger();
    $log->write($order, 'order');
        
    $defaultOrderType = 1;
    $dbOrderTypesList = CSalePersonType::GetList(array(), array("ACTIVE" => "Y"));
    if ($arOrderTypesList = $dbOrderTypesList->Fetch()) {
        $defaultOrderType = $arOrderTypesList['ID'];
    }
    
    $GLOBALS['INTARO_CRM_FROM_HISTORY'] = true;

    if (function_exists('intarocrm_order_pre_persist')) {
Ejemplo n.º 2
0
    COption::SetOptionString($mid, $CRM_PAYMENT_STATUSES, serialize(ICrmOrderActions::clearArr($paymentStatusesArr)));
    COption::SetOptionString($mid, $CRM_PAYMENT, serialize(ICrmOrderActions::clearArr($paymentArr)));
    COption::SetOptionString($mid, $CRM_ORDER_DISCHARGE, $orderDischarge);
    COption::SetOptionString($mid, $CRM_ORDER_PROPS, serialize(ICrmOrderActions::clearArr($orderPropsArr)));
    COption::SetOptionString($mid, $CRM_CONTRAGENT_TYPE, serialize(ICrmOrderActions::clearArr($contragentTypeArr)));
    COption::SetOptionString($mid, $CRM_LEGAL_DETAILS, serialize(ICrmOrderActions::clearArr($legalDetailsArr)));
    COption::SetOptionString($mid, $CRM_CUSTOM_FIELDS, serialize(ICrmOrderActions::clearArr($customFieldsArr)));
    COption::SetOptionString($mid, $CRM_DISCOUNT_TEXT, $discount_text);
    COption::SetOptionString($mid, $CRM_DISCOUNT_PHOTO, $discount_photo);
    COption::SetOptionString($mid, $CRM_DISCOUNT_VIDEO, $discount_video);
    $uri .= '&ok=Y';
    LocalRedirect($uri);
} else {
    $api_host = COption::GetOptionString($mid, $CRM_API_HOST_OPTION, 0);
    $api_key = COption::GetOptionString($mid, $CRM_API_KEY_OPTION, 0);
    $api = new RetailCrm\RestApi($api_host, $api_key);
    //prepare crm lists
    try {
        $arResult['orderTypesList'] = $api->orderTypesList()->orderTypes;
        $arResult['deliveryTypesList'] = $api->deliveryTypesList()->deliveryTypes;
        $arResult['deliveryServicesList'] = $api->deliveryServicesList()->deliveryServices;
        $arResult['paymentTypesList'] = $api->paymentTypesList()->paymentTypes;
        $arResult['paymentStatusesList'] = $api->paymentStatusesList()->paymentStatuses;
        // --statuses
        $arResult['paymentList'] = $api->orderStatusesList()->statuses;
        $arResult['paymentGroupList'] = $api->orderStatusGroupsList()->statusGroups;
        // -- statuses groups
        $arResult['sitesList'] = $APPLICATION->ConvertCharsetArray($api->sitesList()->sites, 'utf-8', SITE_CHARSET);
    } catch (\RetailCrm\Exception\CurlException $e) {
        ICrmOrderActions::eventLog('intaro.crm/options.php', 'RetailCrm\\RestApi::*List::CurlException', $e->getCode() . ': ' . $e->getMessage());
        echo CAdminMessage::ShowMessage(GetMessage('ERR_' . $e->getCode()));
Ejemplo n.º 3
0
 public function onReviewSend($userId, $productId, $data, $orderId = null)
 {
     if (empty($userId) || $userId < 1) {
         throw new \RetailCrm\Exception\WrongParamException('Некорректный ID пользователя');
         return true;
     } elseif (empty($productId) || $productId < 1) {
         throw new \RetailCrm\Exception\WrongParamException('Некорректный ID заказа');
         return true;
     } elseif ($orderId < 1 && $orderId != null) {
         throw new \RetailCrm\Exception\WrongParamException('Некорректный ID продукта');
         return true;
     } elseif (empty($data) || !is_array($data)) {
         throw new \RetailCrm\Exception\WrongParamException('Массив не передан, либо имеет некорректный тип');
         return true;
     } elseif (!(isset($data['reviewText']) && isset($data['reviewMark']) && isset($data['reviewType']))) {
         throw new \RetailCrm\Exception\WrongParamException('Отсутствуют необходимые элементы массива');
         return true;
     } else {
         if ($orderId == null) {
             CModule::IncludeModule('sale');
             $arOrder = array('ID' => 'DESC');
             $dbOrders = CSaleOrder::GetList($arOrder, array('USER_ID' => $userId), false, false, array('ID'));
             while ($order = $dbOrders->Fetch()) {
                 $order_ids[] = $order['ID'];
             }
             $basket = CSaleBasket::GetList($arOrder, array('ORDER_ID' => $order_ids, 'PRODUCT_ID' => self::getProductOffers($productId)), false, false, array('PRODUCT_ID', 'ORDER_ID'))->Fetch();
             if ($basket) {
                 $orderId = $basket['ORDER_ID'];
             } else {
                 throw new \RetailCrm\Exception\WrongParamException('Не найден заказ');
                 return true;
             }
         }
         $api_host = COption::GetOptionString(self::$MODULE_ID, self::$CRM_API_HOST_OPTION, 0);
         $api_key = COption::GetOptionString(self::$MODULE_ID, self::$CRM_API_KEY_OPTION, 0);
         $api = new RetailCrm\RestApi($api_host, $api_key);
         $data['reviewProductId'] = $productId;
         $data['reviewDiscount'] = self::getReviewDiscount('discount_' . $data['reviewType']);
         unset($data['reviewType']);
         $data['reviewApproved'] = 1;
         $order = array('externalId' => $orderId, 'customFields' => $data);
         try {
             $api->orderEdit($order);
         } catch (\RetailCrm\Exception\CurlException $e) {
             throw new \RetailCrm\Exception\DispatchInterruptException('Не удалось передать заказ в RetailCrm');
         }
     }
     return true;
 }
Ejemplo n.º 4
0
 /**
  *
  * History update, cron usage only
  * @global CUser $USER
  * @return boolean
  */
 public static function orderHistory()
 {
     global $USER;
     if (is_object($USER) == false) {
         $USER = new RetailUser();
     }
     if (!CModule::IncludeModule("iblock")) {
         self::eventLog('ICrmOrderActions::orderHistory', 'iblock', 'module not found');
         return false;
     }
     if (!CModule::IncludeModule("sale")) {
         self::eventLog('ICrmOrderActions::orderHistory', 'sale', 'module not found');
         return false;
     }
     if (!CModule::IncludeModule("catalog")) {
         self::eventLog('ICrmOrderActions::orderHistory', 'catalog', 'module not found');
         return false;
     }
     $api_host = COption::GetOptionString(self::$MODULE_ID, self::$CRM_API_HOST_OPTION, 0);
     $api_key = COption::GetOptionString(self::$MODULE_ID, self::$CRM_API_KEY_OPTION, 0);
     $optionsOrderTypes = array_flip(unserialize(COption::GetOptionString(self::$MODULE_ID, self::$CRM_ORDER_TYPES_ARR, 0)));
     $optionsDelivTypes = array_flip(unserialize(COption::GetOptionString(self::$MODULE_ID, self::$CRM_DELIVERY_TYPES_ARR, 0)));
     $optionsPayTypes = array_flip(unserialize(COption::GetOptionString(self::$MODULE_ID, self::$CRM_PAYMENT_TYPES, 0)));
     $optionsPayStatuses = array_flip(unserialize(COption::GetOptionString(self::$MODULE_ID, self::$CRM_PAYMENT_STATUSES, 0)));
     // --statuses
     $optionsPayment = array_flip(unserialize(COption::GetOptionString(self::$MODULE_ID, self::$CRM_PAYMENT, 0)));
     $optionsOrderProps = unserialize(COption::GetOptionString(self::$MODULE_ID, self::$CRM_ORDER_PROPS, 0));
     $optionsLegalDetails = unserialize(COption::GetOptionString(self::$MODULE_ID, self::$CRM_LEGAL_DETAILS, 0));
     $optionsContragentType = unserialize(COption::GetOptionString(self::$MODULE_ID, self::$CRM_CONTRAGENT_TYPE, 0));
     $optionsSitesList = unserialize(COption::GetOptionString(self::$MODULE_ID, self::$CRM_SITES_LIST, 0));
     $optionsCustomFields = unserialize(COption::GetOptionString(self::$MODULE_ID, self::$CRM_CUSTOM_FIELDS, 0));
     foreach ($optionsOrderProps as $code => $value) {
         if (isset($optionsLegalDetails[$code])) {
             $optionsOrderProps[$code] = array_merge($optionsOrderProps[$code], $optionsLegalDetails[$code]);
         }
         if (isset($optionsCustomFields[$code])) {
             $optionsOrderProps[$code] = array_merge($optionsOrderProps[$code], $optionsCustomFields[$code]);
         }
         $optionsOrderProps[$code]['location'] = 'LOCATION';
         if (array_search('CITY', $optionsOrderProps[$code]) == false) {
             $optionsOrderProps[$code]['city'] = 'CITY';
         }
         if (array_search('ZIP', $optionsOrderProps[$code]) == false) {
             $optionsOrderProps[$code]['index'] = 'ZIP';
         }
     }
     $api = new RetailCrm\RestApi($api_host, $api_key);
     $dateStart = COption::GetOptionString(self::$MODULE_ID, self::$CRM_ORDER_HISTORY_DATE, null);
     if (is_null($dateStart)) {
         $dateStart = new \DateTime();
         $dateStart = $dateStart->format('Y-m-d H:i:s');
     }
     try {
         $orderHistory = $api->orderHistory($dateStart);
     } catch (\RetailCrm\Exception\CurlException $e) {
         self::eventLog('ICrmOrderActions::orderHistory', 'RetailCrm\\RestApi::orderHistory::CurlException', $e->getCode() . ': ' . $e->getMessage());
         return false;
     }
     $orderHistory = isset($orderHistory['orders']) ? $orderHistory['orders'] : array();
     $log = new Logger();
     $log->write($orderHistory, 'history');
     $dateFinish = $api->getGeneratedAt();
     if (is_null($dateFinish) || $dateFinish == false) {
         $dateFinish = new \DateTime();
     }
     $defaultOrderType = 1;
     $dbOrderTypesList = CSalePersonType::GetList(array(), array("ACTIVE" => "Y"));
     if ($arOrderTypesList = $dbOrderTypesList->Fetch()) {
         $defaultOrderType = $arOrderTypesList['ID'];
     }
     $GLOBALS['INTARO_CRM_FROM_HISTORY'] = true;
     foreach ($orderHistory as $order) {
         if (function_exists('intarocrm_order_pre_persist')) {
             $order = intarocrm_order_pre_persist($order);
         }
         if (!isset($order['externalId'])) {
             // custom orderType function
             if (function_exists('intarocrm_set_order_type')) {
                 $orderType = intarocrm_set_order_type($order);
                 if ($orderType) {
                     $optionsOrderTypes[$order['orderType']] = $orderType;
                 } else {
                     $optionsOrderTypes[$order['orderType']] = $defaultOrderType;
                 }
             }
             // we dont need new orders without any customers (can check only for externalId)
             if (!isset($order['customer']['externalId'])) {
                 if (!isset($order['customer']['id'])) {
                     continue;
                 }
                 $registerNewUser = true;
                 if (!isset($order['customer']['email']) || $order['customer']['email'] == '') {
                     $login = $order['customer']['email'] = uniqid('user_' . time()) . '@crm.com';
                 } else {
                     $dbUser = CUser::GetList($by = 'ID', $sort = 'ASC', array('=EMAIL' => $order['email']));
                     switch ($dbUser->SelectedRowsCount()) {
                         case 0:
                             $login = $order['customer']['email'];
                             break;
                         case 1:
                             $arUser = $dbUser->Fetch();
                             $registeredUserID = $arUser['ID'];
                             $registerNewUser = false;
                             break;
                         default:
                             $login = uniqid('user_' . time()) . '@crm.com';
                             break;
                     }
                 }
                 if ($registerNewUser === true) {
                     $userPassword = uniqid();
                     $newUser = new CUser();
                     $arFields = array("NAME" => self::fromJSON($order['customer']['firstName']), "LAST_NAME" => self::fromJSON($order['customer']['lastName']), "EMAIL" => $order['customer']['email'], "LOGIN" => $login, "LID" => "ru", "ACTIVE" => "Y", "PASSWORD" => $userPassword, "CONFIRM_PASSWORD" => $userPassword);
                     $registeredUserID = $newUser->Add($arFields);
                     if ($registeredUserID === false) {
                         self::eventLog('ICrmOrderActions::orderHistory', 'CUser::Register', 'Error register user');
                         continue;
                     }
                     try {
                         $api->customerFixExternalIds(array(array('id' => $order['customer']['id'], 'externalId' => $registeredUserID)));
                     } catch (\RetailCrm\Exception\CurlException $e) {
                         self::eventLog('ICrmOrderActions::orderHistory', 'RetailCrm\\RestApi::customerFixExternalIds::CurlException', $e->getCode() . ': ' . $e->getMessage());
                         continue;
                     }
                 }
                 $order['customer']['externalId'] = $registeredUserID;
             }
             // new order
             $newOrderFields = array('LID' => CSite::GetDefSite(), 'PERSON_TYPE_ID' => isset($optionsOrderTypes[$order['orderType']]) ? $optionsOrderTypes[$order['orderType']] : $defaultOrderType, 'PAYED' => 'N', 'CANCELED' => 'N', 'STATUS_ID' => 'N', 'PRICE' => 0, 'CURRENCY' => CCurrency::GetBaseCurrency(), 'USER_ID' => $order['customer']['externalId'], 'PAY_SYSTEM_ID' => 0, 'PRICE_DELIVERY' => 0, 'DELIVERY_ID' => 0, 'DISCOUNT_VALUE' => 0, 'USER_DESCRIPTION' => '');
             if (count($optionsSitesList) > 1 && ($lid = array_search($order['site'], $optionsSitesList))) {
                 $newOrderFields['LID'] = $lid;
             }
             $externalId = CSaleOrder::Add($newOrderFields);
             if (!isset($order['externalId'])) {
                 try {
                     $api->orderFixExternalIds(array(array('id' => $order['id'], 'externalId' => $externalId)));
                 } catch (\RetailCrm\Exception\CurlException $e) {
                     self::eventLog('ICrmOrderActions::orderHistory', 'RetailCrm\\RestApi::orderFixExternalIds::CurlException', $e->getCode() . ': ' . $e->getMessage());
                     continue;
                 }
             }
             $order['externalId'] = $externalId;
         }
         if (isset($order['externalId']) && $order['externalId']) {
             // custom orderType function
             if (function_exists('intarocrm_set_order_type')) {
                 $orderType = intarocrm_set_order_type($order);
                 if ($orderType) {
                     $optionsOrderTypes[$order['orderType']] = $orderType;
                 } else {
                     $optionsOrderTypes[$order['orderType']] = $defaultOrderType;
                 }
             }
             $arFields = CSaleOrder::GetById($order['externalId']);
             // incorrect order
             if ($arFields === false || empty($arFields)) {
                 continue;
             }
             $LID = $arFields['LID'];
             $userId = $arFields['USER_ID'];
             if (isset($order['customer']['externalId']) && !is_null($order['customer']['externalId'])) {
                 $userId = $order['customer']['externalId'];
             }
             $rsOrderProps = CSaleOrderPropsValue::GetList(array(), array('ORDER_ID' => $arFields['ID']));
             $arUpdateProps = array();
             while ($ar = $rsOrderProps->Fetch()) {
                 $prop = CSaleOrderProps::GetByID($ar['ORDER_PROPS_ID']);
                 $arUpdateProps[$ar['CODE']] = array('ID' => $ar['ID'], 'TYPE' => $prop['TYPE'], 'VALUE' => $ar['VALUE']);
             }
             $order['fio'] = trim(implode(' ', array(isset($order['lastName']) ? $order['lastName'] : '', isset($order['firstName']) ? $order['firstName'] : '', isset($order['patronymic']) ? $order['patronymic'] : '')));
             if (isset($order['delivery']['address']['city'])) {
                 $order['location'] = $order['delivery']['address']['city'];
             }
             if (isset($order['orderType']) && isset($optionsOrderTypes[$order['orderType']])) {
                 if (isset($optionsOrderProps[$arFields['PERSON_TYPE_ID']])) {
                     foreach ($optionsOrderProps[$arFields['PERSON_TYPE_ID']] as $code => $value) {
                         if (in_array($code, array_keys($order)) === false && isset($optionsOrderProps[$optionsOrderTypes[$order['orderType']]][$code])) {
                             $order[$code] = $arUpdateProps[$optionsOrderProps[$arFields['PERSON_TYPE_ID']][$code]]['VALUE'];
                         }
                     }
                 }
                 //update ordertype
                 CSaleOrder::Update($order['externalId'], array('PERSON_TYPE_ID' => $optionsOrderTypes[$order['orderType']]));
                 $arProp = CSaleOrderProps::GetList(array(), array('PERSON_TYPE_ID' => $optionsOrderTypes[$order['orderType']]));
                 $typeParam = array();
                 while ($ar = $arProp->Fetch()) {
                     $typeParam[$ar['CODE']] = $ar['CODE'];
                 }
                 foreach (array_diff_key($arUpdateProps, $typeParam) as $code => $param) {
                     if (isset($arUpdateProps[$code])) {
                         CSaleOrderPropsValue::Delete($param['ID']);
                     }
                 }
                 $arFields['PERSON_TYPE_ID'] = $optionsOrderTypes[$order['orderType']];
             }
             array_walk_recursive(self::clearArr($order), 'self::recursiveUpdate', array('update' => $arUpdateProps, 'type' => $arFields['PERSON_TYPE_ID'], 'options' => $optionsOrderProps, 'orderId' => $order['externalId']));
             foreach ($order['items'] as $item) {
                 if (isset($item['deleted']) && $item['deleted']) {
                     if ($p = CSaleBasket::GetList(array(), array('ORDER_ID' => $order['externalId'], 'PRODUCT_ID' => $item['id']))->Fetch()) {
                         if (!CSaleBasket::Delete($p['ID'])) {
                             self::eventLog('ICrmOrderActions::orderHistory', 'CSaleBasket::Delete', 'Error element delete');
                         }
                     } else {
                         $prp = CSaleBasket::GetPropsList(array(), array("ORDER_ID" => $order['externalId'], "CODE" => 'ID', "VALUE" => $item['id']))->Fetch();
                         if (!CSaleBasket::Delete($prp['BASKET_ID'])) {
                             self::eventLog('ICrmOrderActions::orderHistory', 'CSaleBasket::Delete', 'Error castom element delete');
                         }
                     }
                     continue;
                 }
                 if (isset($item['offer']) === false && isset($item['offer']['externalId']) === false) {
                     continue;
                 }
                 $res = CIBlockElement::GetByID($item['offer']['externalId'])->Fetch();
                 if ($res) {
                     $p = CSaleBasket::GetList(array(), array('ORDER_ID' => $order['externalId'], 'PRODUCT_ID' => $item['offer']['externalId']))->Fetch();
                     if ($p == false) {
                         $p = CIBlockElement::GetByID($item['offer']['externalId'])->GetNext();
                         $iblock = CIBlock::GetByID($p['IBLOCK_ID'])->Fetch();
                         $p['CATALOG_XML_ID'] = $iblock['XML_ID'];
                         $p['PRODUCT_XML_ID'] = $p['XML_ID'];
                         unset($p['XML_ID']);
                     } elseif ($propResult = CSaleBasket::GetPropsList(array(''), array('BASKET_ID' => $p['ID']))) {
                         while ($r = $propResult->Fetch()) {
                             unset($r['ID']);
                             unset($r['BASKET_ID']);
                             $p['PROPS'][] = $r;
                         }
                     }
                     $arProduct = array();
                     if (isset($item['created']) && $item['created'] == true) {
                         $productPrice = GetCatalogProductPrice($item['offer']['externalId'], COption::GetOptionString(self::$MODULE_ID, self::$CRM_CATALOG_BASE_PRICE, 0));
                         $arProduct = array('FUSER_ID' => $userId, 'ORDER_ID' => $order['externalId'], 'QUANTITY' => $item['quantity'], 'CURRENCY' => $productPrice['CURRENCY'], 'LID' => $LID, 'PRODUCT_ID' => $item['offer']['externalId'], 'PRODUCT_PRICE_ID' => $p['PRODUCT_PRICE_ID'], 'WEIGHT' => $p['WEIGHT'], 'DELAY' => $p['DELAY'], 'CAN_BUY' => $p['CAN_BUY'], 'MODULE' => $p['MODULE'], 'NOTES' => $item['comment'] ?: $p['NOTES'], 'PRODUCT_PROVIDER_CLASS' => $p['PRODUCT_PROVIDER_CLASS'], 'DETAIL_PAGE_URL' => $p['DETAIL_PAGE_URL'], 'CATALOG_XML_ID' => $p['CATALOG_XML_ID'], 'PRODUCT_XML_ID' => $p['PRODUCT_XML_ID'], 'CUSTOM_PRICE' => 'Y');
                     }
                     if (isset($item['isCanceled']) == false) {
                         if (isset($item['initialPrice']) && $item['initialPrice']) {
                             $arProduct['PRICE'] = (double) $item['initialPrice'];
                         }
                         if (isset($item['discount'])) {
                             $arProduct['DISCOUNT_PRICE'] = $item['discount'];
                         }
                         if (isset($item['discountPercent'])) {
                             $arProduct['DISCOUNT_VALUE'] = $item['discountPercent'];
                             $newPrice = round($arProduct['PRICE'] / 100 * (100 - $arProduct['DISCOUNT_VALUE']), 2);
                             $arProduct['DISCOUNT_PRICE'] = $arProduct['DISCOUNT_PRICE'] + $arProduct['PRICE'] - $newPrice;
                         }
                         if (isset($item['discount']) || isset($item['discountPercent'])) {
                             $arProduct['PRICE'] -= $arProduct['DISCOUNT_PRICE'];
                         }
                         if (isset($item['offer']['name']) && $item['offer']['name']) {
                             $arProduct['NAME'] = self::fromJSON($item['offer']['name']);
                         }
                         $arProduct = self::updateCancelProp($arProduct, 0);
                     } elseif (isset($item['isCanceled'])) {
                         $arProduct['PRICE'] = 0;
                         $arProduct = self::updateCancelProp($arProduct, 1);
                     }
                     if (isset($item['created']) && $item['created'] == true) {
                         if (!Add2BasketByProductID($item['offer']['externalId'], $item['quantity'], $arProduct, $p['PROPS'])) {
                             self::eventLog('ICrmOrderActions::orderHistory', 'Add2BasketByProductID', 'Error element add');
                         }
                         continue;
                     }
                     if (count($p['PROPS']) > 0) {
                         $arProduct['PROPS'] = $p['PROPS'];
                     }
                     if (isset($item['quantity']) && $item['quantity']) {
                         $arProduct['QUANTITY'] = $item['quantity'];
                     }
                     if (isset($item['offer']['name']) && $item['offer']['name']) {
                         $arProduct['NAME'] = self::fromJSON($item['offer']['name']);
                     }
                     if (!CSaleBasket::Update($p['ID'], $arProduct)) {
                         self::eventLog('ICrmOrderActions::orderHistory', 'CSaleBasket::Update', 'Error element update');
                     }
                     CSaleBasket::DeleteAll($userId);
                 } else {
                     $arProduct = array();
                     if (isset($item['created']) && $item['created'] == true) {
                         $arProduct = array('FUSER_ID' => $userId, 'ORDER_ID' => $order['externalId'], 'LID' => $LID, 'NOTES' => $item['comment']);
                     }
                     if (isset($item['isCanceled']) == false) {
                         if (isset($item['initialPrice']) && $item['initialPrice']) {
                             $arProduct['PRICE'] = (double) $item['initialPrice'];
                         }
                         if (isset($item['discount'])) {
                             $arProduct['DISCOUNT_PRICE'] = $item['discount'];
                         }
                         if (isset($item['discountPercent'])) {
                             $arProduct['DISCOUNT_VALUE'] = $item['discountPercent'];
                             $newPrice = round($arProduct['PRICE'] / 100 * (100 - $arProduct['DISCOUNT_VALUE']), 2);
                             $arProduct['DISCOUNT_PRICE'] = $arProduct['DISCOUNT_PRICE'] + $arProduct['PRICE'] - $newPrice;
                         }
                         if (isset($item['discount']) || isset($item['discountPercent'])) {
                             $arProduct['PRICE'] -= $arProduct['DISCOUNT_PRICE'];
                         }
                         if (isset($item['offer']['name']) && $item['offer']['name']) {
                             $arProduct['NAME'] = self::fromJSON($item['offer']['name']);
                         }
                         $arProduct = self::updateCancelProp($arProduct, 0);
                     } elseif (isset($item['isCanceled'])) {
                         $arProduct['PRICE'] = 0;
                         $arProduct = self::updateCancelProp($arProduct, 1);
                     }
                     if (isset($item['quantity']) && $item['quantity']) {
                         $arProduct['QUANTITY'] = $item['quantity'];
                     }
                     if (isset($item['offer']['name']) && $item['offer']['name']) {
                         $arProduct['NAME'] = self::fromJSON($item['offer']['name']);
                     }
                     if (isset($item['created']) && $item['created'] == true) {
                         $iBlocks = unserialize(COption::GetOptionString(self::$MODULE_ID, self::$CRM_CATALOG_IBLOCKS, 0));
                         $iBlock = array_shift($iBlocks);
                         $newSection = new CIBlockSection();
                         $newSectionFields = array("ACTIVE" => 'N', "IBLOCK_ID" => $iBlock, "NAME" => 'RetailCRM', "CODE" => 'RetailCRM');
                         $resSection = $newSection->Add($newSectionFields);
                         if (!$resSection) {
                             self::eventLog('ICrmOrderActions::orderHistory', 'CIBlockSection::Add', 'Error castom section add');
                             continue;
                         }
                         $arLoadProductArray = array("IBLOCK_SECTION_ID" => $resSection, "IBLOCK_ID" => $iBlock, "NAME" => $item['offer']['name'] ? $item['offer']['name'] : 'RetailCrmElement', "CODE" => 'RetailCrmElement', "ACTIVE" => 'Y');
                         $el = new CIBlockElement();
                         $PRODUCT_ID = $el->Add($arLoadProductArray, false, false, true);
                         if (!$PRODUCT_ID) {
                             self::eventLog('ICrmOrderActions::orderHistory', 'CIBlockElement::Add', 'Error castom element add');
                             continue;
                         }
                         if (!CCatalogProduct::Add(array("ID" => $PRODUCT_ID))) {
                             self::eventLog('ICrmOrderActions::orderHistory', 'CCatalogProduct::Add', 'Error product add');
                             continue;
                         }
                         $arFields = array("PRODUCT_ID" => $PRODUCT_ID, "CATALOG_GROUP_ID" => COption::GetOptionString(self::$MODULE_ID, self::$CRM_CATALOG_BASE_PRICE, 0), "PRICE" => $item['initialPrice'] ? $item['initialPrice'] : 1, "CURRENCY" => CCurrency::GetBaseCurrency());
                         if (!CPrice::Add($arFields)) {
                             self::eventLog('ICrmOrderActions::orderHistory', 'CPrice::Add', 'Error price add');
                             continue;
                         }
                         $Params = array(array('NAME' => 'id', 'CODE' => 'ID', 'VALUE' => $item['offer']['externalId']));
                         if (!Add2BasketByProductID($PRODUCT_ID, $item['quantity'], $arProduct, $Params)) {
                             self::eventLog('ICrmOrderActions::orderHistory', 'Add2BasketByProductID', 'Error add to basket');
                             continue;
                         }
                         if (!CIBlockSection::Delete($resSection)) {
                             self::eventLog('ICrmOrderActions::orderHistory', 'CIBlockSection::Delete', 'Error delete section');
                             continue;
                         }
                         continue;
                     }
                     $prp = CSaleBasket::GetPropsList(array(), array("ORDER_ID" => $order['externalId'], "CODE" => 'ID', "VALUE" => $item['offer']['externalId']))->Fetch();
                     CSaleBasket::Update($prp['BASKET_ID'], $arProduct);
                 }
             }
             if (isset($order['delivery']) === false || isset($order['delivery']['cost']) === false) {
                 $order['delivery']['cost'] = $arFields['PRICE_DELIVERY'];
             }
             if (isset($order['summ']) === false || $order['summ'] <= 0) {
                 $order['summ'] = $arFields['PRICE'] - $arFields['PRICE_DELIVERY'];
             }
             $wasCanaceled = $arFields['CANCELED'] == 'Y' ? true : false;
             if (isset($optionsDelivTypes[$order['delivery']['code']])) {
                 $resultDeliveryTypeId = $optionsDelivTypes[$order['delivery']['code']];
             } else {
                 $resultDeliveryTypeId = isset($order['delivery']['service']) && isset($order['delivery']['service']['code']) ? reset(explode(":", $arFields['DELIVERY_ID'], 1)) : $arFields['DELIVERY_ID'];
             }
             if (isset($order['delivery']['service']) && isset($order['delivery']['service']['code'])) {
                 $deliveryHandler = reset(CSaleDeliveryHandler::GetBySID($resultDeliveryTypeId)->arResult);
                 if (count($deliveryHandler) > 0 && array_key_exists($order['delivery']['service']['code'], $deliveryHandler['PROFILES'])) {
                     $resultDeliveryTypeId = $resultDeliveryTypeId . ':' . $order['delivery']['service']['code'];
                 }
             }
             // orderUpdate
             $arFields = self::clearArr(array('PRICE_DELIVERY' => $order['delivery']['cost'], 'PRICE' => $order['summ'] + (double) $order['delivery']['cost'], 'DATE_MARKED' => $order['markDatetime'], 'USER_ID' => $userId, 'PAY_SYSTEM_ID' => $optionsPayTypes[$order['paymentType']], 'DELIVERY_ID' => $resultDeliveryTypeId, 'STATUS_ID' => $optionsPayStatuses[$order['status']], 'REASON_CANCELED' => self::fromJSON($order['statusComment']), 'USER_DESCRIPTION' => self::fromJSON($order['customerComment']), 'COMMENTS' => self::fromJSON($order['managerComment'])));
             if (isset($order['discount'])) {
                 $arFields['DISCOUNT_VALUE'] = $order['discount'];
                 $arFields['PRICE'] -= $order['discount'];
             }
             if (!empty($arFields)) {
                 CSaleOrder::Update($order['externalId'], $arFields);
             }
             if (isset($order['status']) && $order['status']) {
                 if (isset($optionsPayStatuses[$order['status']]) && $optionsPayStatuses[$order['status']]) {
                     // set STATUS_ID
                     CSaleOrder::StatusOrder($order['externalId'], $optionsPayStatuses[$order['status']]);
                     if ($wasCanaceled && $optionsPayStatuses[$order['status']] != 'YY') {
                         CSaleOrder::CancelOrder($order['externalId'], "N", $order['statusComment']);
                     } elseif ($optionsPayStatuses[$order['status']] == 'YY') {
                         CSaleOrder::CancelOrder($order['externalId'], "Y", $order['statusComment']);
                     }
                 }
             }
             // set PAYED
             if (isset($order['paymentStatus']) && $order['paymentStatus'] && $optionsPayment[$order['paymentStatus']]) {
                 CSaleOrder::PayOrder($order['externalId'], $optionsPayment[$order['paymentStatus']]);
             }
             if (function_exists('intarocrm_order_post_persist')) {
                 intarocrm_order_post_persist($order);
             }
         }
     }
     if (count($orderHistory) > 0) {
         COption::SetOptionString(self::$MODULE_ID, self::$CRM_ORDER_HISTORY_DATE, $dateFinish->format('Y-m-d H:i:s'));
     }
     $GLOBALS['INTARO_CRM_FROM_HISTORY'] = false;
     return true;
 }