From b2ae04bebb383c7da1ac0c7132b315b44ad38459 Mon Sep 17 00:00:00 2001 From: "m.korolev" Date: Wed, 25 Sep 2013 20:36:49 +0400 Subject: [PATCH 1/9] fix complex array storage in bitrix --- intaro.intarocrm/export/export_run.php | 25 ++++++++ intaro.intarocrm/export/export_setup.php | 58 ++++++++++++++----- intaro.intarocrm/install/index.php | 33 +++++++---- intaro.intarocrm/install/step5.php | 20 +++---- .../lang/ru/icml_export_setup.php | 9 ++- 5 files changed, 107 insertions(+), 38 deletions(-) diff --git a/intaro.intarocrm/export/export_run.php b/intaro.intarocrm/export/export_run.php index b0ddb912..34b4f19b 100644 --- a/intaro.intarocrm/export/export_run.php +++ b/intaro.intarocrm/export/export_run.php @@ -10,6 +10,31 @@ if (!CModule::IncludeModule("catalog")) if (!CModule::IncludeModule("intaro.intarocrm")) return; +$iblockProperties = Array( + "article" => "article", + "manufacturer" => "manufacturer", + "color" =>"color", + "weight" => "weight", + "size" => "size", + ); +$IBLOCK_PROPERTY_SKU = array(); +foreach ($iblockProperties as $prop) { + $skuProps = ('IBLOCK_PROPERTY_SKU' . "_" . $prop); + $skuProps = $$skuProps; + foreach ($skuProps as $iblock => $val) { + $IBLOCK_PROPERTY_SKU[$iblock][$prop] = $val; + } +} +$IBLOCK_PROPERTY_PRODUCT = array(); +foreach ($iblockProperties as $prop) { + $skuProps = "IBLOCK_PROPERTY_PRODUCT" . "_" . $prop; + $skuProps = $$skuProps; + foreach ($skuProps as $iblock => $val) { + $IBLOCK_PROPERTY_PRODUCT[$iblock][$prop] = $val; + } +} + + $loader = new ICMLLoader(); $loader->iblocks = $IBLOCK_EXPORT; $loader->propertiesSKU = $IBLOCK_PROPERTY_SKU; diff --git a/intaro.intarocrm/export/export_setup.php b/intaro.intarocrm/export/export_setup.php index 008ddf9a..8c4e8176 100644 --- a/intaro.intarocrm/export/export_setup.php +++ b/intaro.intarocrm/export/export_setup.php @@ -1,6 +1,12 @@ "article", + "manufacturer" => "manufacturer", + "color" =>"color", + "weight" => "weight", + "size" => "size", + ); if(!check_bitrix_sessid()) return; @@ -8,19 +14,31 @@ __IncludeLang(GetLangFileName($_SERVER["DOCUMENT_ROOT"]."/bitrix/modules/intaro. if (($ACTION == 'EXPORT' || $ACTION == 'EXPORT_EDIT' || $ACTION == 'EXPORT_COPY') && $STEP == 1) { + + if (isset($arOldSetupVars['SETUP_FILE_NAME'])) $SETUP_FILE_NAME = $arOldSetupVars['SETUP_FILE_NAME']; if (isset($arOldSetupVars['SETUP_PROFILE_NAME'])) $SETUP_PROFILE_NAME = $arOldSetupVars['SETUP_PROFILE_NAME']; if (isset($arOldSetupVars['IBLOCK_EXPORT'])) $IBLOCK_EXPORT = $arOldSetupVars['IBLOCK_EXPORT']; - if (isset($arOldSetupVars['IBLOCK_PROPERTY_SKU'])) - $IBLOCK_PROPERTY_SKU = $arOldSetupVars['IBLOCK_PROPERTY_SKU']; - if (isset($arOldSetupVars['IBLOCK_PROPERTY_PRODUCT'])) - $IBLOCK_PROPERTY_PRODUCT = $arOldSetupVars['IBLOCK_PROPERTY_PRODUCT']; + + $IBLOCK_PROPERTY_SKU = array(); + foreach ($iblockProperties as $prop) { + foreach ($arOldSetupVars['IBLOCK_PROPERTY_SKU'. '_' . $prop] as $iblock => $val) { + $IBLOCK_PROPERTY_SKU[$iblock][$prop] = $val; + } + } + $IBLOCK_PROPERTY_PRODUCT = array(); + foreach ($iblockProperties as $prop) { + foreach ($arOldSetupVars['IBLOCK_PROPERTY_PRODUCT'. '_' . $prop] as $iblock => $val) { + $IBLOCK_PROPERTY_PRODUCT[$iblock][$prop] = $val; + } + } } + if ($STEP>1) { @@ -76,11 +94,11 @@ if ($STEP==1) } $iblockPropertiesName = Array( - "article" => "Артикул", - "manufacturer" => "Производитель", - "color" => "Цвет", - "weight" => "Вес", - "size" => "Размер", + "article" => GetMessage("PROPERTY_ARTICLE_HEADER_NAME"), + "manufacturer" => GetMessage("PROPERTY_MANUFACTURER_HEADER_NAME"), + "color" => GetMessage("PROPERTY_COLOR_HEADER_NAME"), + "weight" => GetMessage("PROPERTY_WEIGHT_HEADER_NAME"), + "size" => GetMessage("PROPERTY_SIZE_HEADER_NAME"), ); $iblockPropertiesHint = Array( @@ -209,14 +227,14 @@ if ($STEP==1) -
Выгружаемое свойство
+
-
Свойство товара
+
-
Свойство торгового предложения
+
@@ -233,7 +251,7 @@ if ($STEP==1) " - name="IBLOCK_PROPERTY_SKU[][]" + name="IBLOCK_PROPERTY_SKU_[]" class="property-export" onchange="propertyChange(this);"> @@ -422,11 +440,19 @@ if ($STEP==1) + "> - + "> diff --git a/intaro.intarocrm/install/index.php b/intaro.intarocrm/install/index.php index 2a8e5cec..b587945a 100755 --- a/intaro.intarocrm/install/index.php +++ b/intaro.intarocrm/install/index.php @@ -823,15 +823,27 @@ class intaro_intarocrm extends CModule { else $iblocks = $_POST['IBLOCK_EXPORT']; - if(!isset($_POST['IBLOCK_PROPERTY_SKU'])) - $arResult['errCode'] = 'ERR_FIELDS_SKU'; - else - $propertiesSKU = $_POST['IBLOCK_PROPERTY_SKU']; + $iblockProperties = Array( + "article" => "article", + "manufacturer" => "manufacturer", + "color" =>"color", + "weight" => "weight", + "size" => "size", + ); - if(!isset($_POST['IBLOCK_PROPERTY_PRODUCT'])) - $arResult['errCode'] = 'ERR_FIELDS_PRODUCT'; - else - $propertiesProduct = $_POST['IBLOCK_PROPERTY_PRODUCT']; + $propertiesSKU = array(); + foreach ($iblockProperties as $prop) { + foreach ($_POST['IBLOCK_PROPERTY_SKU'. '_' . $prop] as $iblock => $val) { + $propertiesSKU[$iblock][$prop] = $val; + } + } + + $propertiesProduct = array(); + foreach ($iblockProperties as $prop) { + foreach ($_POST['IBLOCK_PROPERTY_PRODUCT'. '_' . $prop] as $iblock => $val) { + $propertiesProduct[$iblock][$prop] = $val; + } + } if (!isset($_POST['SETUP_FILE_NAME'])) $arResult['errCode'] = 'ERR_FIELDS_FILE'; @@ -1091,14 +1103,13 @@ class intaro_intarocrm extends CModule { $strVars .= 'IBLOCK_EXPORT[' . $key . ']=' . $val . '&'; foreach ($propertiesSKU as $iblock => $arr) foreach ($arr as $id => $val) - $strVars .= 'IBLOCK_PROPERTY_SKU[' . $iblock . '][' . $id . ']=' . $val . '&'; + $strVars .= 'IBLOCK_PROPERTY_SKU_' . $id . '[' . $iblock . ']=' . $val . '&'; foreach ($propertiesProduct as $iblock => $arr) foreach ($arr as $id => $val) - $strVars .= 'IBLOCK_PROPERTY_PRODUCT[' . $iblock . '][' . $id . ']=' . $val . '&'; + $strVars .= 'IBLOCK_PROPERTY_PRODUCT_' . $id . '[' . $iblock . ']=' . $val . '&'; $strVars .= 'SETUP_FILE_NAME=' . urlencode($filename); return $strVars; } - } \ No newline at end of file diff --git a/intaro.intarocrm/install/step5.php b/intaro.intarocrm/install/step5.php index a3389bcb..9378847a 100644 --- a/intaro.intarocrm/install/step5.php +++ b/intaro.intarocrm/install/step5.php @@ -35,11 +35,11 @@ if (!empty($oldValues)) { } $iblockPropertiesName = Array( - "article" => "Артикул", - "manufacturer" => "Производитель", - "color" => "Цвет", - "weight" => "Вес", - "size" => "Размер", + "article" => GetMessage("PROPERTY_ARTICLE_HEADER_NAME"), + "manufacturer" => GetMessage("PROPERTY_MANUFACTURER_HEADER_NAME"), + "color" => GetMessage("PROPERTY_COLOR_HEADER_NAME"), + "weight" => GetMessage("PROPERTY_WEIGHT_HEADER_NAME"), + "size" => GetMessage("PROPERTY_SIZE_HEADER_NAME"), ); $iblockPropertiesHint = Array( @@ -165,14 +165,14 @@ if (!empty($oldValues)) { -
Выгружаемое свойство
+
-
Свойство товара
+
-
Свойство торгового предложения
+
@@ -189,7 +189,7 @@ if (!empty($oldValues)) { " - name="IBLOCK_PROPERTY_SKU[][]" + name="IBLOCK_PROPERTY_SKU_[]" class="property-export" onchange="propertyChange(this);"> diff --git a/intaro.intarocrm/lang/ru/icml_export_setup.php b/intaro.intarocrm/lang/ru/icml_export_setup.php index ee440a48..7dc07010 100644 --- a/intaro.intarocrm/lang/ru/icml_export_setup.php +++ b/intaro.intarocrm/lang/ru/icml_export_setup.php @@ -17,5 +17,12 @@ $MESS["PROFILE_NAME"] = "Имя профиля"; $MESS["SETTINGS_INFOBLOCK"] = "Настройки инфоблоков"; $MESS["SETTINGS_EXPORT"] = "Настройки экспорта"; $MESS["CHECK_ALL_INFOBLOCKS"] = "Выбрать все инфоблоки "; - +$MESS["LOADED_PROPERTY"] = "Выгружаемое свойство"; +$MESS["PROPERTY_PRODUCT_HEADER_NAME"] = "Свойство товара"; +$MESS["PROPERTY_OFFER_HEADER_NAME"] = "Свойство торгового предложения"; +$MESS["PROPERTY_ARTICLE_HEADER_NAME"] = "Артикул"; +$MESS["PROPERTY_MANUFACTURER_HEADER_NAME"] = "Производитель"; +$MESS["PROPERTY_COLOR_HEADER_NAME"] = "Цвет"; +$MESS["PROPERTY_WEIGHT_HEADER_NAME"] = "Вес"; +$MESS["PROPERTY_SIZE_HEADER_NAME"] = "Размер"; ?> \ No newline at end of file From 8508c6bebb8312be6e015ca2ea731f40f10c229c Mon Sep 17 00:00:00 2001 From: Grisha Pomadchin Date: Wed, 2 Oct 2013 17:45:28 +0400 Subject: [PATCH 2/9] new orders create --- .../classes/general/ICrmOrderActions.php | 108 +++++++++++------- 1 file changed, 69 insertions(+), 39 deletions(-) diff --git a/intaro.intarocrm/classes/general/ICrmOrderActions.php b/intaro.intarocrm/classes/general/ICrmOrderActions.php index 5b5353cd..fd47708f 100755 --- a/intaro.intarocrm/classes/general/ICrmOrderActions.php +++ b/intaro.intarocrm/classes/general/ICrmOrderActions.php @@ -279,6 +279,11 @@ class ICrmOrderActions return true; } + $defaultSiteId = 0; + $rsSites = CSite::GetList($by, $sort, array('DEF' => 'Y')); + while ($ar = $rsSites->Fetch()) + $defaultSiteId = $ar['LID']; + $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); @@ -294,42 +299,46 @@ class ICrmOrderActions $api = new IntaroCrm\RestApi($api_host, $api_key); $orderHistory = $api->orderHistory(); - + // pushing existing orders foreach ($orderHistory as $order) { + var_dump($order); - if(!isset($order['externalId']) && !$order['externalId']) { - + // выбрасываем заказы от 'новых клиентов' + if(!isset($order['customer']) && !$order['customer']) continue; + + if(!isset($order['externalId']) && !$order['externalId']) { // new order - /*array( - 'LID' => SITE_ID, //<----! - 'PERSON_TYPE_ID' => 1, // <------! + $newOrderFields = array( + 'LID' => $defaultSiteId, //<----! + 'PERSON_TYPE_ID' => $optionsOrderTypes[$order['orderType']], // <------! 'PAYED' => 'N', 'CANCELED' => 'N', 'STATUS_ID' => 'N', 'PRICE' => 0, 'CURRENCY' => 'RUB', - 'USER_ID' => IntVal($USER->GetID()), // <--------! + 'USER_ID' => $order['customer'], // <--------! 'PAY_SYSTEM_ID' => 0, 'PRICE_DELIVERY' => 0, 'DELIVERY_ID' => 0, 'DISCOUNT_VALUE' => 0, 'USER_DESCRIPTION' => '' ); + + if(isset($order['number']) && $order['number']) + $newOrderFields['ACCOUNT_NUMBER'] = $order['number']; - $order['externalId'] = CSaleOrder::Add(array()); + $order['externalId'] = CSaleOrder::Add($newOrderFields); - $api->orderFixExternalIds(array($order['id'], $order['externalId'])); + $api->orderFixExternalIds(array(array('id' => $order['id'], 'externalId' => $order['externalId']))); if ($api->getStatusCode() != 200) { //handle err - write log & continue self::eventLog('ICrmOrderActions::orderHistory', 'IntaroCrm\RestApi::orderFixExternalIds', $api->getLastError()); continue; } - - */ } if(isset($order['externalId']) && $order['externalId']) { @@ -347,6 +356,8 @@ class ICrmOrderActions $rsOrderProps = CSaleOrderPropsValue::GetList(array(), array('ORDER_ID' => $arFields['ID'])); while ($ar = $rsOrderProps->Fetch()) { + if($order['externalId'] == 45) + var_dump($ar); if (isset($order['deliveryAddress']) && $order['deliveryAddress']) { switch ($ar['CODE']) { case 'CITY': if (isset($order['deliveryAddress']['city'])) @@ -459,7 +470,7 @@ class ICrmOrderActions self::fromJSON($order['deliveryAddress']['house']), $order['externalId']); } } - + if (isset($order['phone'])) self::addOrderProperty($optionsOrderProps[$arFields['PERSON_TYPE_ID']]['phone'], self::fromJSON($order['phone']), $order['externalId']); @@ -479,13 +490,24 @@ class ICrmOrderActions self::addOrderProperty($optionsOrderProps[$arFields['PERSON_TYPE_ID']]['fio'], implode(" ", $contactName), $order['externalId']); - /*foreach($order['items'] as $item) { + foreach($order['items'] as $item) { + if(!isset($item['offer']) && !$item['offer']['externalId']) + continue; + $p = CSaleBasket::GetList( array('PRODUCT_ID' => 'ASC'), array('ORDER_ID' => $order['externalId'], 'PRODUCT_ID' => $item['offer']['externalId']))->Fetch(); - if(!$p) // if not found - continue; + if(!$p) + $p = CIBlockElement::GetByID($item['offer']['externalId'])->Fetch(); + + var_dump($p); + + var_dump(GetCatalogProductPrice($item['offer']['externalId'], 1)); + //if(!$p) // if not found + // continue; + + //echo 1; // del from basket if(isset($item['deleted']) && $item['deleted']) { @@ -494,18 +516,19 @@ class ICrmOrderActions } // change existing basket items - if(!isset($item['offer']) && !$item['offer']['externalId']) - continue; + $arProduct = array(); // create new if(isset($item['created']) && $item['created']) { + $productPrice = GetCatalogProductPrice($item['offer']['externalId'], 1); + $arProduct = array( 'FUSER_ID' => $userId, 'ORDER_ID' => $order['externalId'], 'QUANTITY' => $item['quantity'], - 'CURRENCY' => $p['CURRENCY'], + 'CURRENCY' => $productPrice['CURRENCY'], 'LID' => $LID, 'PRODUCT_ID' => $item['offer']['externalId'], 'PRODUCT_PRICE_ID' => $p['PRODUCT_PRICE_ID'], @@ -536,29 +559,34 @@ class ICrmOrderActions if (isset($item['offer']['name']) && $item['offer']['name']) $arProduct['NAME'] = $item['offer']['name']; - CSaleBasket::Add($arProduct); - continue; + + var_dump($arProduct); + + var_dump(CSaleBasket::Add($arProduct)); + //continue; } - // update old - if(isset($item['initialPrice']) && $item['initialPrice']) - $arProduct['PRICE'] = (double) $item['initialPrice']; - - if(isset($item['dicount']) && $item['discount']){ - $arProduct['PRICE'] = $arProducts['PRICE'] - (double) $item['disount']; - $arProduct['DISCOUNT_PRICE'] = $item['discount']; + if ($p) { + // update old + if (isset($item['initialPrice']) && $item['initialPrice']) + $arProduct['PRICE'] = (double) $item['initialPrice']; + + if (isset($item['dicount']) && $item['discount']) { + $arProduct['PRICE'] = $arProducts['PRICE'] - (double) $item['disount']; + $arProduct['DISCOUNT_PRICE'] = $item['discount']; + } + + if (isset($item['discountPercent']) && $item['discountPercent']) { + //$arProducts['PRICE'] -- how ? + $arProduct['DISCOUNT_VALUE'] = $item['discountPercent']; + } + + if (isset($item['offer']['name']) && $item['offer']['name']) + $arProduct['NAME'] = $item['offer']['name']; + + CSaleBasket::Update($p['ID'], $arProduct); } - - if(isset($item['discountPercent']) && $item['discountPercent']) { - //$arProducts['PRICE'] -- how ? - $arProduct['DISCOUNT_VALUE'] = $item['discountPercent']; - } - - if(isset($item['offer']['name']) && $item['offer']['name']) - $arProduct['NAME'] = $item['offer']['name']; - - CSaleBasket::Update($p['ID'], $arProduct); - }*/ + } // orderUpdate $arFields = self::clearArr(array( @@ -686,7 +714,7 @@ class ICrmOrderActions if($send) $customer = $api->customerEdit($customer); - + // error pushing customer if (!$customer) { //handle err @@ -806,6 +834,8 @@ class ICrmOrderActions 'managerComment' => $arFields['COMMENTS'], 'createdAt' => $createdAt, 'deliveryAddress' => $resOrderDeliveryAddress, + 'discount' => $arFields['DISCOUNT_PRICE'], + 'discountPercent' => $arFields['DISCOUNT_VALUE'], 'items' => $items ); From 3644c385b33cd020102dbbb94c819046ea163433 Mon Sep 17 00:00:00 2001 From: Grisha Pomadchin Date: Wed, 2 Oct 2013 17:49:24 +0400 Subject: [PATCH 3/9] rm var_dump --- .../classes/general/ICrmOrderActions.php | 55 ++++++------------- 1 file changed, 18 insertions(+), 37 deletions(-) diff --git a/intaro.intarocrm/classes/general/ICrmOrderActions.php b/intaro.intarocrm/classes/general/ICrmOrderActions.php index fd47708f..830b1140 100755 --- a/intaro.intarocrm/classes/general/ICrmOrderActions.php +++ b/intaro.intarocrm/classes/general/ICrmOrderActions.php @@ -302,7 +302,6 @@ class ICrmOrderActions // pushing existing orders foreach ($orderHistory as $order) { - var_dump($order); // выбрасываем заказы от 'новых клиентов' if(!isset($order['customer']) && !$order['customer']) @@ -356,8 +355,6 @@ class ICrmOrderActions $rsOrderProps = CSaleOrderPropsValue::GetList(array(), array('ORDER_ID' => $arFields['ID'])); while ($ar = $rsOrderProps->Fetch()) { - if($order['externalId'] == 45) - var_dump($ar); if (isset($order['deliveryAddress']) && $order['deliveryAddress']) { switch ($ar['CODE']) { case 'CITY': if (isset($order['deliveryAddress']['city'])) @@ -500,14 +497,6 @@ class ICrmOrderActions if(!$p) $p = CIBlockElement::GetByID($item['offer']['externalId'])->Fetch(); - - var_dump($p); - - var_dump(GetCatalogProductPrice($item['offer']['externalId'], 1)); - //if(!$p) // if not found - // continue; - - //echo 1; // del from basket if(isset($item['deleted']) && $item['deleted']) { @@ -516,8 +505,6 @@ class ICrmOrderActions } // change existing basket items - - $arProduct = array(); // create new @@ -558,34 +545,28 @@ class ICrmOrderActions if (isset($item['offer']['name']) && $item['offer']['name']) $arProduct['NAME'] = $item['offer']['name']; - - - var_dump($arProduct); - - var_dump(CSaleBasket::Add($arProduct)); - //continue; + + CSaleBasket::Add($arProduct); } - - if ($p) { - // update old - if (isset($item['initialPrice']) && $item['initialPrice']) - $arProduct['PRICE'] = (double) $item['initialPrice']; - if (isset($item['dicount']) && $item['discount']) { - $arProduct['PRICE'] = $arProducts['PRICE'] - (double) $item['disount']; - $arProduct['DISCOUNT_PRICE'] = $item['discount']; - } + // update old + if (isset($item['initialPrice']) && $item['initialPrice']) + $arProduct['PRICE'] = (double) $item['initialPrice']; - if (isset($item['discountPercent']) && $item['discountPercent']) { - //$arProducts['PRICE'] -- how ? - $arProduct['DISCOUNT_VALUE'] = $item['discountPercent']; - } - - if (isset($item['offer']['name']) && $item['offer']['name']) - $arProduct['NAME'] = $item['offer']['name']; - - CSaleBasket::Update($p['ID'], $arProduct); + if (isset($item['dicount']) && $item['discount']) { + $arProduct['PRICE'] = $arProducts['PRICE'] - (double) $item['disount']; + $arProduct['DISCOUNT_PRICE'] = $item['discount']; } + + if (isset($item['discountPercent']) && $item['discountPercent']) { + //$arProducts['PRICE'] -- how ? + $arProduct['DISCOUNT_VALUE'] = $item['discountPercent']; + } + + if (isset($item['offer']['name']) && $item['offer']['name']) + $arProduct['NAME'] = $item['offer']['name']; + + CSaleBasket::Update($p['ID'], $arProduct); } // orderUpdate From 323b67d400ae60974071b1edd9815b8aa995568d Mon Sep 17 00:00:00 2001 From: Grisha Pomadchin Date: Fri, 4 Oct 2013 16:36:43 +0400 Subject: [PATCH 4/9] history fix duplicate products --- .../classes/general/ICrmOrderActions.php | 26 +++++++++++++++---- 1 file changed, 21 insertions(+), 5 deletions(-) diff --git a/intaro.intarocrm/classes/general/ICrmOrderActions.php b/intaro.intarocrm/classes/general/ICrmOrderActions.php index 830b1140..6c1f5438 100755 --- a/intaro.intarocrm/classes/general/ICrmOrderActions.php +++ b/intaro.intarocrm/classes/general/ICrmOrderActions.php @@ -14,6 +14,7 @@ class ICrmOrderActions protected static $CRM_ORDER_SITES = 'sites_ids'; protected static $CRM_ORDER_PROPS = 'order_props'; protected static $CRM_ORDER_FAILED_IDS = 'order_failed_ids'; + protected static $CRM_ORDER_HISTORY_DATE = 'order_history_date'; /** * Mass order uploading, without repeating; always returns true, but writes error log @@ -298,7 +299,12 @@ class ICrmOrderActions $api = new IntaroCrm\RestApi($api_host, $api_key); - $orderHistory = $api->orderHistory(); + $dateStart = COption::GetOptionString(self::$MODULE_ID, self::$CRM_ORDER_HISTORY_DATE, null); + + $orderHistory = $api->orderHistory($dateStart); + + if($dateStart) + $dateStart = new \DateTime($dateStart); // pushing existing orders foreach ($orderHistory as $order) { @@ -351,7 +357,6 @@ class ICrmOrderActions if(isset($order['customer']) && $order['customer']) $userId = $order['customer']; $LID = $arFields['LID']; - $rsOrderProps = CSaleOrderPropsValue::GetList(array(), array('ORDER_ID' => $arFields['ID'])); while ($ar = $rsOrderProps->Fetch()) { @@ -509,6 +514,7 @@ class ICrmOrderActions // create new if(isset($item['created']) && $item['created']) { + $productPrice = GetCatalogProductPrice($item['offer']['externalId'], 1); $arProduct = array( @@ -546,7 +552,8 @@ class ICrmOrderActions if (isset($item['offer']['name']) && $item['offer']['name']) $arProduct['NAME'] = $item['offer']['name']; - CSaleBasket::Add($arProduct); + //CSaleBasket::Add($arProduct); + } // update old @@ -567,8 +574,14 @@ class ICrmOrderActions $arProduct['NAME'] = $item['offer']['name']; CSaleBasket::Update($p['ID'], $arProduct); + CSaleBasket::DeleteAll($userId); } - + + $dateInsert = new \DateTime($arFields['DATE_INSERT']); + + if(!$dateStart || ($dateInsert > $dateStart)) + $dateStart = $dateInsert; + // orderUpdate $arFields = self::clearArr(array( 'PRICE_DELIVERY' => $order['deliveryCost'], @@ -589,7 +602,10 @@ class ICrmOrderActions CSaleOrder::Update($order['externalId'], $arFields); } - } + } + + if(count($orderHistory)) + COption::SetOptionString(self::$MODULE_ID, self::$CRM_ORDER_HISTORY_DATE, $dateStart->format('Y-m-d H:i:s')); return true; } From 0a84b8f2baee1cce5749d4845bfba2093dadded0 Mon Sep 17 00:00:00 2001 From: Grisha Pomadchin Date: Fri, 4 Oct 2013 16:56:57 +0400 Subject: [PATCH 5/9] changed working prot --- .../classes/general/ICMLLoader.php | 393 -------- .../classes/general/ICrmOrderActions.php | 932 ------------------ intaro.intarocrm/classes/general/RestApi.php | 499 ---------- .../classes/general/events/ICrmOrderEvent.php | 251 ----- intaro.intarocrm/description.ru | 1 + intaro.intarocrm/export/export_run.php | 44 - intaro.intarocrm/export/export_setup.php | 468 --------- intaro.intarocrm/include.php | 10 - .../install/export/intarocrm_run.php | 3 - .../install/export/intarocrm_setup.php | 3 - intaro.intarocrm/install/index.php | 89 +- intaro.intarocrm/install/step1.php | 62 -- intaro.intarocrm/install/step2.php | 260 ----- intaro.intarocrm/install/step3.php | 103 -- intaro.intarocrm/install/step4.php | 203 ---- intaro.intarocrm/install/step5.php | 405 -------- intaro.intarocrm/install/step6.php | 11 - intaro.intarocrm/install/unstep1.php | 8 - intaro.intarocrm/install/version.php | 6 - .../lang/ru/classes/general/ICMLLoader.php | 2 - intaro.intarocrm/lang/ru/export_crm.php | 109 -- .../lang/ru/export_setup_templ.php | 124 --- .../lang/ru/icml_export_setup.php | 28 - intaro.intarocrm/lang/ru/install/index.php | 34 - intaro.intarocrm/lang/ru/install/step2.php | 20 - intaro.intarocrm/lang/ru/install/step3.php | 34 - intaro.intarocrm/lang/ru/install/step4.php | 12 - intaro.intarocrm/lang/ru/install/step5.php | 24 - intaro.intarocrm/lang/ru/install/step6.php | 18 - intaro.intarocrm/lang/ru/install/unstep1.php | 3 - intaro.intarocrm/lang/ru/options.php | 55 -- .../lang/ru/{install => }/step1.php | 2 +- intaro.intarocrm/options.php | 4 + intaro.intarocrm/updater.php | 9 + 34 files changed, 50 insertions(+), 4179 deletions(-) delete mode 100644 intaro.intarocrm/classes/general/ICMLLoader.php delete mode 100755 intaro.intarocrm/classes/general/ICrmOrderActions.php delete mode 100644 intaro.intarocrm/classes/general/RestApi.php delete mode 100644 intaro.intarocrm/classes/general/events/ICrmOrderEvent.php create mode 100644 intaro.intarocrm/description.ru delete mode 100644 intaro.intarocrm/export/export_run.php delete mode 100644 intaro.intarocrm/export/export_setup.php delete mode 100755 intaro.intarocrm/include.php delete mode 100644 intaro.intarocrm/install/export/intarocrm_run.php delete mode 100644 intaro.intarocrm/install/export/intarocrm_setup.php delete mode 100755 intaro.intarocrm/install/step1.php delete mode 100755 intaro.intarocrm/install/step2.php delete mode 100755 intaro.intarocrm/install/step3.php delete mode 100644 intaro.intarocrm/install/step4.php delete mode 100644 intaro.intarocrm/install/step5.php delete mode 100644 intaro.intarocrm/install/step6.php delete mode 100755 intaro.intarocrm/install/unstep1.php delete mode 100755 intaro.intarocrm/install/version.php delete mode 100644 intaro.intarocrm/lang/ru/classes/general/ICMLLoader.php delete mode 100644 intaro.intarocrm/lang/ru/export_crm.php delete mode 100644 intaro.intarocrm/lang/ru/export_setup_templ.php delete mode 100644 intaro.intarocrm/lang/ru/icml_export_setup.php delete mode 100755 intaro.intarocrm/lang/ru/install/index.php delete mode 100755 intaro.intarocrm/lang/ru/install/step2.php delete mode 100755 intaro.intarocrm/lang/ru/install/step3.php delete mode 100644 intaro.intarocrm/lang/ru/install/step4.php delete mode 100755 intaro.intarocrm/lang/ru/install/step5.php delete mode 100755 intaro.intarocrm/lang/ru/install/step6.php delete mode 100755 intaro.intarocrm/lang/ru/install/unstep1.php delete mode 100755 intaro.intarocrm/lang/ru/options.php rename intaro.intarocrm/lang/ru/{install => }/step1.php (92%) create mode 100644 intaro.intarocrm/updater.php diff --git a/intaro.intarocrm/classes/general/ICMLLoader.php b/intaro.intarocrm/classes/general/ICMLLoader.php deleted file mode 100644 index af3ea5ac..00000000 --- a/intaro.intarocrm/classes/general/ICMLLoader.php +++ /dev/null @@ -1,393 +0,0 @@ -iblocks) < count($this->articleProperties)) - return false; - - $this->PrepareSettings(); - - $this->PrepareFile(); - - $this->PreWriteCatalog(); - - $categories = $this->GetCategories(); - - $this->WriteCategories($categories); - - $this->PreWriteOffers(); - $this->BuildOffers($categories); - $this->PostWriteOffers(); - - $this->PostWriteCatalog(); - - $this->CloseFile(); - return true; - - } - - protected function PrepareSettings() - { - foreach ($this->propertiesSKU as $iblock => $arr) { - foreach ($arr as $id => $sku) { - $this->propertiesSKU[$iblock][$id] = strtoupper($sku); - } - } - foreach ($this->propertiesProduct as $iblock => $arr) { - foreach ($arr as $id => $prod) { - $this->propertiesProduct[$iblock][$id] = strtoupper($prod); - } - } - } - - protected function PrepareValue($text) - { - $newText = $this->application->ConvertCharset($text, LANG_CHARSET, $this->encoding); - $newText = strip_tags($newText); - $newText = str_replace("&", "&", $newText); - return $newText; - } - - protected function PrepareFile() - { - $fullFilename = $_SERVER["DOCUMENT_ROOT"] . $this->filename; - CheckDirPath($fullFilename); - - if (!$this->fp = @fopen($fullFilename, "w")) - return false; - else - return true; - } - - protected function PreWriteCatalog() - { - @fwrite($this->fp, "PrepareValue(Date("Y-m-d H:i:s")) . "\">\n - \n - " . $this->PrepareValue(COption::GetOptionString("main", "site_name", ""))."\n - " . $this->PrepareValue(COption::GetOptionString("main", "site_name", ""))."\n" - ); - - } - - protected function WriteCategories($categories) - { - $stringCategories = ""; - @fwrite($this->fp, "\n"); - foreach ($categories as $category) { - $stringCategories .= $this->BuildCategory($category); - } - @fwrite($this->fp, $stringCategories); - @fwrite($this->fp, "\n"); - } - protected function PreWriteOffers() - { - @fwrite($this->fp, "\n"); - } - - protected function PostWriteOffers() - { - @fwrite($this->fp, "\n"); - } - - protected function WriteOffers($offers) - { - @fwrite($this->fp, $offers); - } - - protected function PostWriteCatalog() - { - @fwrite($this->fp, "\n - \n"); - } - - protected function CloseFile() - { - @fclose($this->fp); - } - - - protected function GetCategories() - { - $categories = array(); - foreach ($this->iblocks as $id) - { - $filter = Array( - "IBLOCK_ID" => $id, - "ACTIVE" => "Y", - "IBLOCK_ACTIVE" => "Y", - "GLOBAL_ACTIVE" => "Y" - ); - - $dbRes = CIBlockSection::GetList(array("left_margin" => "asc"), $filter); - $hasCategories = false; - while ($arRes = $dbRes->Fetch()) - { - $categories[$arRes['ID']] = $arRes; - $hasCategories = true; - } - if (!$hasCategories) - { - $iblock = CIBlock::GetByID($id)->Fetch(); - - $arRes = Array(); - $arRes['ID'] = $this->mainSection + $id; - $arRes['IBLOCK_SECTION_ID'] = 0; - $arRes['NAME'] = sprintf(GetMessage('ROOT_CATEGORY_FOR_CATALOG'), $iblock['NAME']); - $categories[$arRes['ID']] = $arRes; - } - } - return $categories; - - } - - protected function BuildCategory($arCategory) - { - return " - PrepareValue($arCategory["ID"]) . "\"" - . ( intval($arCategory["IBLOCK_SECTION_ID"] ) > 0 ? - " parentId=\"" . $this->PrepareValue($arCategory["IBLOCK_SECTION_ID"]) . "\"" - :"") - . ">" - . $this->PrepareValue($arCategory["NAME"]) - . "\n"; - - } - - protected function BuildOffers(&$allCategories) - { - foreach ($this->iblocks as $key => $id) - { - $iblock['IBLOCK_DB'] = CIBlock::GetByID($id)->Fetch(); - $iblockOffer = CCatalogSKU::GetInfoByProductIBlock($id); - - $arSelect = Array ( - "ID", - "LID", - "IBLOCK_ID", - "IBLOCK_SECTION_ID", - "ACTIVE", - "ACTIVE_FROM", - "ACTIVE_TO", - "NAME", - "DETAIL_PICTURE", - "DETAIL_TEXT", - "DETAIL_PICTURE", - "LANG_DIR", - "DETAIL_PAGE_URL" - ); - - foreach ($this->propertiesProduct[$id] as $key => $propProduct) { - if ($this->propertiesProduct[$id][$key] != "") - $arSelect[] = "PROPERTY_" . $propProduct; - } - - - $filter = Array ( - "IBLOCK_ID" => $id, - "ACTIVE_DATE" => "Y", - "ACTIVE" => "Y", - "INCLUDE_SUBSECTIONS" => "Y" - ); - $count = 0; - $dbResProducts = CIBlockElement::GetList(array(), $filter, false, false, $arSelect); - $stringOffers = ""; - while ($product = $dbResProducts->GetNextElement()) { - - $product = $product->GetFields(); - - // Get properties of product - $resPropertiesProduct = Array(); - foreach ($this->propertiesProduct[$id] as $key => $propProduct) { - $resPropertiesProduct[$key] = ""; - if ($propProduct != "") { - $propDesc = CIBlockProperty::GetByID($propProduct, $id)->GetNext(); - - if ($propDesc['PROPERTY_TYPE'] == 'E') { - $el = CIBlockElement::GetById($product["PROPERTY_" . $propProduct . "_VALUE"])->Fetch(); - $resPropertiesProduct[$key] = $el['NAME']; - } else { - $resPropertiesProduct[$key] = $product["PROPERTY_" . $propProduct . "_VALUE"]; - } - } - } - - // Get categories of product - $categories = Array(); - $dbResCategories = CIBlockElement::GetElementGroups($product['ID'], true); - while ($arResCategory = $dbResCategories->Fetch()) { - $categories[$arResCategory["ID"]] = array( - 'ID' => $arResCategory["ID"], - 'NAME' => $arResCategory["NAME"], - ); - } - if (count($categories) == 0) { - - $catId = $this->mainSection + $id; - $categories[$catId] = $allCategories[$catId]; - } - - - $existOffer = false; - if (!empty($iblockOffer['IBLOCK_ID'])) { - - $arFilterOffer = Array ( - 'IBLOCK_ID' => $iblockOffer['IBLOCK_ID'], - 'PROPERTY_' . $iblockOffer['SKU_PROPERTY_ID'] => $product["ID"] - ); - $arSelectOffer = Array ( - 'ID', - "NAME", - "DETAIL_TEXT", - "DETAIL_PAGE_URL", - "DETAIL_PICTURE" - ); - - foreach ($this->propertiesSKU[$id] as $key => $propSKU) { - if ($this->propertiesSKU[$id][$key] != "") - $arSelectOffer[] = "PROPERTY_" . $propSKU; - } - - $rsOffers = CIBlockElement::GetList(array(), $arFilterOffer, false, false, $arSelectOffer); - while ($arOffer = $rsOffers->GetNext()) { - - $offer = CCatalogProduct::GetByID($arOffer['ID']); - $arOffer['QUANTITY'] = $offer["QUANTITY"]; - - $arOffer['PRODUCT_ID'] = $product["ID"]; - $arOffer['DETAIL_PAGE_URL'] = $product["DETAIL_PAGE_URL"]; - $arOffer['DETAIL_PICTURE'] = $product["DETAIL_PICTURE"]; - $arOffer['PREVIEW_PICTURE'] = $product["PREVIEW_PICTURE"]; - $arOffer['PRODUCT_NAME'] = $product["NAME"]; - - // Get properties of offer - - foreach ($this->propertiesSKU[$id] as $key => $propSKU) { - if ($propSKU != "") { - $propDesc = CIBlockProperty::GetByID($propSKU,$arOffer['ID'])->GetNext(); - - if ($propDesc['PROPERTY_TYPE'] == 'E') { - $el = CIBlockElement::GetById($product["PROPERTY_" . $propSKU . "_VALUE"])->Fetch(); - $arOffer[$key] = $el['NAME']; - } else { - $arOffer[$key] = $arOffer["PROPERTY_" . $propSKU . "_VALUE"]; - } - } - } - - foreach ($resPropertiesProduct as $key => $propProduct) { - if ($this->propertiesProduct[$id][$key] != "") - $arOffer[$key] = $propProduct; - } - - $dbPrice = GetCatalogProductPrice($arOffer["ID"],1); - $arOffer['PRICE'] = $dbPrice['PRICE']; - - $stringOffers .= $this->BuildOffer($arOffer, $categories, $iblock); - $existOffer = true; - } - } - if (!$existOffer) { - - $offer = CCatalogProduct::GetByID($product['ID']); - $product['QUANTITY'] = $offer["QUANTITY"]; - - $product['PRODUCT_ID'] = $product["ID"]; - $product['PRODUCT_NAME'] = $product["NAME"]; - - foreach ($resPropertiesProduct as $key => $propProduct) { - if ($this->propertiesProduct[$id][$key] != "") - $product[$key] = $propProduct; - } - - $dbPrice = GetCatalogProductPrice($product["ID"],1); - $product['PRICE'] = $dbPrice['PRICE']; - - $stringOffers .= $this->BuildOffer($product, $categories, $iblock); - } - - $count++; - if ($count == 1000) { - $this->WriteOffers($stringOffers); - $stringOffers = ""; - } - - } - - if ($stringOffers != "") { - $this->WriteOffers($stringOffers); - $stringOffers = ""; - } - - } - } - - - protected function BuildOffer($arOffer, $categories, $iblock) - { - $offer = ""; - $offer .= "PrepareValue($arOffer["ID"]) . "\" ". - "productId=\"" . $this->PrepareValue($arOffer["PRODUCT_ID"]) . "\" ". - "quantity=\"" . $this->PrepareValue(DoubleVal($arOffer['QUANTITY'])) . "\">\n"; - - $offer .= "http://" . $this->PrepareValue($iblock['IBLOCK_DB']['SERVER_NAME']) . $this->PrepareValue($arOffer['DETAIL_PAGE_URL']) . "\n"; - - $offer .= "" . $this->PrepareValue($arOffer['PRICE']) . "\n"; - foreach ($categories as $category) - $offer .= "" . $category['ID'] . "\n"; - - $detailPicture = intval($arOffer["DETAIL_PICTURE"]); - $previewPicture = intval($arOffer["PREVIEW_PICTURE"]); - - if ($detailPicture > 0 || $previewPicture > 0) - { - $picture = $detailPicture; - if ($picture <= 0) { - $picture = $previewPicture; - } - - if ($arFile = CFile::GetFileArray($picture)) - { - if(substr($arFile["SRC"], 0, 1) == "/") - $strFile = "http://" . $this->PrepareValue($iblock['IBLOCK_DB']['SERVER_NAME']) . implode("/", array_map("rawurlencode", explode("/", $arFile["SRC"]))); - elseif(preg_match("/^(http|https):\\/\\/(.*?)\\/(.*)\$/", $arFile["SRC"], $match)) - $strFile = "http://" . $this->PrepareValue($match[2]) . '/' . implode("/", array_map("rawurlencode", explode("/", $this->PrepareValue($match[3])))); - else - $strFile = $arFile["SRC"]; - $offer .= "" . $this->PrepareValue($strFile) . "\n"; - } - } - - $offer .= "" . $this->PrepareValue($arOffer["NAME"]) . "\n"; - - $offer .= "" . $this->PrepareValue($arOffer["EXTERNAL_ID"]) . "\n"; - $offer .= "" . $this->PrepareValue($arOffer["PRODUCT_NAME"]) . "\n"; - - foreach ($this->propertiesProduct[$iblock['IBLOCK_DB']['ID']] as $key => $propProduct) { - if ($propProduct != "" && $arOffer[$key] != null) - $offer .= "<" . $key . ">" . $this->PrepareValue($arOffer[$key]) . "\n"; - } - - $offer.= "\n"; - return $offer; - } - -} \ No newline at end of file diff --git a/intaro.intarocrm/classes/general/ICrmOrderActions.php b/intaro.intarocrm/classes/general/ICrmOrderActions.php deleted file mode 100755 index 5b5353cd..00000000 --- a/intaro.intarocrm/classes/general/ICrmOrderActions.php +++ /dev/null @@ -1,932 +0,0 @@ - "ASC"), array('>ID' => $lastUpOrderId)); - $dbFailedOrder = CSaleOrder::GetList(array("ID" => "ASC"), array('ID' => $failedIds)); - - $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); - - //saved cat params - $optionsOrderTypes = unserialize(COption::GetOptionString(self::$MODULE_ID, self::$CRM_ORDER_TYPES_ARR, 0)); - $optionsDelivTypes = unserialize(COption::GetOptionString(self::$MODULE_ID, self::$CRM_DELIVERY_TYPES_ARR, 0)); - $optionsPayTypes = unserialize(COption::GetOptionString(self::$MODULE_ID, self::$CRM_PAYMENT_TYPES, 0)); - $optionsPayStatuses = unserialize(COption::GetOptionString(self::$MODULE_ID, self::$CRM_PAYMENT_STATUSES, 0)); // --statuses - $optionsPayment = unserialize(COption::GetOptionString(self::$MODULE_ID, self::$CRM_PAYMENT, 0)); - $optionsSites = unserialize(COption::GetOptionString(self::$MODULE_ID, self::$CRM_ORDER_SITES, 0)); - $optionsOrderProps = unserialize(COption::GetOptionString(self::$MODULE_ID, self::$CRM_ORDER_PROPS, 0)); - - $api = new IntaroCrm\RestApi($api_host, $api_key); - - $arParams = array( - 'optionsOrderTypes' => $optionsOrderTypes, - 'optionsDelivTypes' => $optionsDelivTypes, - 'optionsPayTypes' => $optionsPayTypes, - 'optionsPayStatuses' => $optionsPayStatuses, - 'optionsPayment' => $optionsPayment, - 'optionSites' => $optionsSites, - 'optionsOrderProps' => $optionsOrderProps - ); - - if (!$failed) { - - //packmode - - $orderCount = 0; - - while ($arOrder = $dbOrder->GetNext()) { // here orders by id asc - if (is_array($optionsSites)) - if (!empty($optionsSites)) - if (!in_array($arOrder['LID'], $optionsSites)) - continue; - - $result = self::orderCreate($arOrder, $api, $arParams); - - if (!$result['order'] || !$result['customer']) - continue; - - $orderCount++; - - $resOrders[] = $result['order']; - $resCustomers[] = $result['customer']; - - $lastOrderId = $arOrder['ID']; - - if ($orderCount >= $pSize) { - $customers = $api->customerUpload($resCustomers); - - // error pushing customers - if ($api->getStatusCode() != 201) { - //handle err - //self::eventLog('ICrmOrderActions::uploadOrders', 'IntaroCrm\RestApi::customerUpload', $api->getLastError()); - - if ($api->getStatusCode() != 460) // some orders were sent - return false; // in pack mode return errors - } - - $orders = $api->orderUpload($resOrders); - - // error pushing orders - if ($api->getStatusCode() != 201) { - //handle err - self::eventLog('ICrmOrderActions::uploadOrders', 'IntaroCrm\RestApi::orderUpload', $api->getLastError()); - - if ($api->getStatusCode() != 460) // some orders were sent - return false; // in pack mode return errors - } - - if ($lastOrderId) - COption::SetOptionString(self::$MODULE_ID, self::$CRM_ORDER_LAST_ID, $lastOrderId); - - return true; // end of pack - } - } - if (!empty($resOrders)) { - $customers = $api->customerUpload($resCustomers); - - // error pushing customers - if ($api->getStatusCode() != 201) { - //handle err - //self::eventLog('ICrmOrderActions::uploadOrders', 'IntaroCrm\RestApi::customerUpload', $api->getLastError()); - - if ($api->getStatusCode() != 460) // some orders were sent - return false; // in pack mode return errors - } - - $orders = $api->orderUpload($resOrders); - - // error pushing orders - if ($api->getStatusCode() != 201) { - //handle err - self::eventLog('ICrmOrderActions::uploadOrders', 'IntaroCrm\RestApi::orderUpload', $api->getLastError()); - - if ($api->getStatusCode() != 460) // some orders were sent - return false; // in pack mode return errors - } - } - - if ($lastOrderId) - COption::SetOptionString(self::$MODULE_ID, self::$CRM_ORDER_LAST_ID, $lastOrderId); - - } else { - - // failed orders upload - $orderCount = 0; - $recOrders = array(); - - while ($arOrder = $dbFailedOrder->GetNext()) { // here orders by id asc - if (is_array($optionsSites)) - if (!empty($optionsSites)) - if (!in_array($arOrder['LID'], $optionsSites)) - continue; - - $result = self::orderCreate($arOrder, $api, $arParams); - - if (!$result['order'] || !$result['customer']) - continue; - - $orderCount++; - - $resOrders[] = $result['order']; - $resCustomers[] = $result['customer']; - - $recOrders[] = $arOrder['ID']; - - if ($orderCount >= $pSize) { - $customers = $api->customerUpload($resCustomers); - - // error pushing customers - if ($api->getStatusCode() != 201) { - //handle err - //self::eventLog('ICrmOrderActions::uploadOrders', 'IntaroCrm\RestApi::customerUpload', $api->getLastError()); - - if ($api->getStatusCode() != 460) // some orders were sent - return false; // in pack mode return errors - } - - $orders = $api->orderUpload($resOrders); - - // error pushing orders - if ($api->getStatusCode() != 201) { - //handle err - self::eventLog('ICrmOrderActions::uploadOrders', 'IntaroCrm\RestApi::orderUpload', $api->getLastError()); - - if ($api->getStatusCode() != 460) // some orders were sent - return false; // in pack mode return errors - } - - if (!empty($recOrders)) { - $failedIds = array_merge(array_diff($failedIds, $recOrders)); // clear success ids - COption::SetOptionString(self::$MODULE_ID, self::$CRM_ORDER_FAILED_IDS, serialize($failedIds)); - } - - return true; // end of pack - } - } - if (!empty($resOrders)) { - $customers = $api->customerUpload($resCustomers); - - // error pushing customers - if ($api->getStatusCode() != 201) { - //handle err - //self::eventLog('ICrmOrderActions::uploadOrders', 'IntaroCrm\RestApi::customerUpload', $api->getLastError()); - - if ($api->getStatusCode() != 460) // some orders were sent - return false; // in pack mode return errors - } - - $orders = $api->orderUpload($resOrders); - - // error pushing orders - if ($api->getStatusCode() != 201) { - //handle err - self::eventLog('ICrmOrderActions::uploadOrders', 'IntaroCrm\RestApi::orderUpload', $api->getLastError()); - - if ($api->getStatusCode() != 460) // some orders were sent - return false; // in pack mode return errors - } - } - - if (!empty($recOrders)) { - $failedIds = array_merge(array_diff($failedIds, $recOrders)); // clear success ids - COption::SetOptionString(self::$MODULE_ID, self::$CRM_ORDER_FAILED_IDS, serialize($failedIds)); - } - } - - return true; //all ok! - } - - /** - * - * History update - * @global CUser $USER - * @return boolean - */ - public static function orderHistory() { - global $USER; - - if(!isset($USER) || !$USER) { // for agent; to add order User - $USER = new CUser; - $USER->Update(1, array()); - } - - if (!CModule::IncludeModule("iblock")) { - //handle err - self::eventLog('ICrmOrderActions::orderHistory', 'iblock', 'module not found'); - return true; - } - - if (!CModule::IncludeModule("sale")) { - //handle err - self::eventLog('ICrmOrderActions::orderHistory', 'sale', 'module not found'); - return true; - } - - if (!CModule::IncludeModule("catalog")) { - //handle err - self::eventLog('ICrmOrderActions::orderHistory', 'catalog', 'module not found'); - 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); - - //saved cat params (crm -> bitrix) - $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))); - $optionsSites = unserialize(COption::GetOptionString(self::$MODULE_ID, self::$CRM_ORDER_SITES, 0)); - $optionsOrderProps = unserialize(COption::GetOptionString(self::$MODULE_ID, self::$CRM_ORDER_PROPS, 0)); - - $api = new IntaroCrm\RestApi($api_host, $api_key); - - $orderHistory = $api->orderHistory(); - - // pushing existing orders - foreach ($orderHistory as $order) { - - if(!isset($order['externalId']) && !$order['externalId']) { - - continue; - - // new order - /*array( - 'LID' => SITE_ID, //<----! - 'PERSON_TYPE_ID' => 1, // <------! - 'PAYED' => 'N', - 'CANCELED' => 'N', - 'STATUS_ID' => 'N', - 'PRICE' => 0, - 'CURRENCY' => 'RUB', - 'USER_ID' => IntVal($USER->GetID()), // <--------! - 'PAY_SYSTEM_ID' => 0, - 'PRICE_DELIVERY' => 0, - 'DELIVERY_ID' => 0, - 'DISCOUNT_VALUE' => 0, - 'USER_DESCRIPTION' => '' - ); - - $order['externalId'] = CSaleOrder::Add(array()); - - $api->orderFixExternalIds(array($order['id'], $order['externalId'])); - - if ($api->getStatusCode() != 200) { - //handle err - write log & continue - self::eventLog('ICrmOrderActions::orderHistory', 'IntaroCrm\RestApi::orderFixExternalIds', $api->getLastError()); - continue; - } - - */ - } - - if(isset($order['externalId']) && $order['externalId']) { - $arFields = CSaleOrder::GetById($order['externalId']); - - // incorrect order - if(!$arFields || empty($arFields)) - continue; - - $userId = $arFields['USER_ID']; - if(isset($order['customer']) && $order['customer']) $userId = $order['customer']; - $LID = $arFields['LID']; - - - $rsOrderProps = CSaleOrderPropsValue::GetList(array(), array('ORDER_ID' => $arFields['ID'])); - - while ($ar = $rsOrderProps->Fetch()) { - if (isset($order['deliveryAddress']) && $order['deliveryAddress']) { - switch ($ar['CODE']) { - case 'CITY': if (isset($order['deliveryAddress']['city'])) - CSaleOrderPropsValue::Update($ar['ID'], array('VALUE' => self::fromJSON($order['deliveryAddress']['city']))); - break; - case $optionsOrderProps[$arFields['PERSON_TYPE_ID']]['text']: if (isset($order['deliveryAddress']['text'])) - CSaleOrderPropsValue::Update($ar['ID'], array('VALUE' => self::fromJSON($order['deliveryAddress']['text']))); - break; - case 'LOCATION': if (isset($order['deliveryAddress']['city'])) { - $cityId = self::getLocationCityId($order['deliveryAddress']['city']); - if (!$cityId) - break; - CSaleOrderPropsValue::Update($ar['ID'], array('VALUE' => $cityId)); - } - break; - } - - if (count($optionsOrderProps[$arFields['PERSON_TYPE_ID']] > 4)) { - switch ($ar['CODE']) { - /* case $optionsOrderProps[$arFields['PERSON_TYPE_ID']]['country']: $resOrderDeliveryAddress['country'] = self::toJSON($ar['VALUE']); - break; - case $optionsOrderProps[$arFields['PERSON_TYPE_ID']]['region']: $resOrderDeliveryAddress['region'] = self::toJSON($ar['VALUE']); - break; - case $optionsOrderProps[$arFields['PERSON_TYPE_ID']]['city']: $resOrderDeliveryAddress['city'] = self::toJSON($ar['VALUE']); - break; */ - case $optionsOrderProps[$arFields['PERSON_TYPE_ID']]['street']: if (isset($order['deliveryAddress']['street'])) - CSaleOrderPropsValue::Update($ar['ID'], array('VALUE' => self::fromJSON($order['deliveryAddress']['street']))); - break; - case $optionsOrderProps[$arFields['PERSON_TYPE_ID']]['building']: if (isset($order['deliveryAddress']['building'])) - CSaleOrderPropsValue::Update($ar['ID'], array('VALUE' => self::fromJSON($order['deliveryAddress']['building']))); - break; - case $optionsOrderProps[$arFields['PERSON_TYPE_ID']]['flat']: if (isset($order['deliveryAddress']['flat'])) - CSaleOrderPropsValue::Update($ar['ID'], array('VALUE' => self::fromJSON($order['deliveryAddress']['flat']))); - break; - case $optionsOrderProps[$arFields['PERSON_TYPE_ID']]['intercomcode']: if (isset($order['deliveryAddress']['intercomcode'])) - CSaleOrderPropsValue::Update($ar['ID'], array('VALUE' => self::fromJSON($order['deliveryAddress']['intercomcode']))); - break; - case $optionsOrderProps[$arFields['PERSON_TYPE_ID']]['floor']: if (isset($order['deliveryAddress']['floor'])) - CSaleOrderPropsValue::Update($ar['ID'], array('VALUE' => self::fromJSON($order['deliveryAddress']['floor']))); - break; - case $optionsOrderProps[$arFields['PERSON_TYPE_ID']]['block']: if (isset($order['deliveryAddress']['block'])) - CSaleOrderPropsValue::Update($ar['ID'], array('VALUE' => self::fromJSON($order['deliveryAddress']['block']))); - break; - case $optionsOrderProps[$arFields['PERSON_TYPE_ID']]['house']: if (isset($order['deliveryAddress']['house'])) - CSaleOrderPropsValue::Update($ar['ID'], array('VALUE' => self::fromJSON($order['deliveryAddress']['house']))); - break; - } - } - } - - switch ($ar['CODE']) { - case $optionsOrderProps[$arFields['PERSON_TYPE_ID']]['fio']: - if (isset($order['firstName'])) - $contactName['firstName'] = self::fromJSON($order['firstName']); - if (isset($order['lastName'])) - $contactName['lastName'] = self::fromJSON($order['lastName']); - if (isset($order['patronymic'])) - $contactName['patronymic'] = self::fromJSON($order['patronymic']); - - if (!isset($contactName) || empty($contactName)) - break; - - CSaleOrderPropsValue::Update($ar['ID'], array('VALUE' => implode(" ", $contactName))); - break; - case $optionsOrderProps[$arFields['PERSON_TYPE_ID']]['phone']: if (isset($order['phone'])) - CSaleOrderPropsValue::Update($ar['ID'], array('VALUE' => self::fromJSON($order['phone']))); - break; - case $optionsOrderProps[$arFields['PERSON_TYPE_ID']]['email']: if (isset($order['email'])) - CSaleOrderPropsValue::Update($ar['ID'], array('VALUE' => self::fromJSON($order['email']))); - break; - } - - } - - // here check if smth wasnt added or new propetties - if (isset($order['deliveryAddress']) && $order['deliveryAddress']) { - if (isset($order['deliveryAddress']['city'])) - self::addOrderProperty($optionsOrderProps[$arFields['PERSON_TYPE_ID']]['city'], self::fromJSON($order['deliveryAddress']['city']), $order['externalId']); - - if (isset($order['deliveryAddress']['text'])) - self::addOrderProperty($optionsOrderProps[$arFields['PERSON_TYPE_ID']]['text'], self::fromJSON($order['deliveryAddress']['text']), $order['externalId']); - - if (count($optionsOrderProps[$arFields['PERSON_TYPE_ID']] > 4)) { - if (isset($order['deliveryAddress']['street'])) - self::addOrderProperty($optionsOrderProps[$arFields['PERSON_TYPE_ID']]['street'], - self::fromJSON($order['deliveryAddress']['street']), $order['externalId']); - - if (isset($order['deliveryAddress']['building'])) - self::addOrderProperty($optionsOrderProps[$arFields['PERSON_TYPE_ID']]['building'], - self::fromJSON($order['deliveryAddress']['bulding']), $order['externalId']); - - if (isset($order['deliveryAddress']['flat'])) - self::addOrderProperty($optionsOrderProps[$arFields['PERSON_TYPE_ID']]['flat'], - self::fromJSON($order['deliveryAddress']['flat']), $order['externalId']); - - if (isset($order['deliveryAddress']['intercomcode'])) - self::addOrderProperty($optionsOrderProps[$arFields['PERSON_TYPE_ID']]['intercomcode'], - self::fromJSON($order['deliveryAddress']['intercomcode']), $order['externalId']); - - if (isset($order['deliveryAddress']['floor'])) - self::addOrderProperty($optionsOrderProps[$arFields['PERSON_TYPE_ID']]['floor'], - self::fromJSON($order['deliveryAddress']['floor']), $order['externalId']); - - if (isset($order['deliveryAddress']['block'])) - self::addOrderProperty($optionsOrderProps[$arFields['PERSON_TYPE_ID']]['block'], - self::fromJSON($order['deliveryAddress']['block']), $order['externalId']); - - if (isset($order['deliveryAddress']['house'])) - self::addOrderProperty($optionsOrderProps[$arFields['PERSON_TYPE_ID']]['house'], - self::fromJSON($order['deliveryAddress']['house']), $order['externalId']); - } - } - - if (isset($order['phone'])) - self::addOrderProperty($optionsOrderProps[$arFields['PERSON_TYPE_ID']]['phone'], - self::fromJSON($order['phone']), $order['externalId']); - - if (isset($order['email'])) - self::addOrderProperty($optionsOrderProps[$arFields['PERSON_TYPE_ID']]['email'], - self::fromJSON($order['email']), $order['externalId']); - - if (isset($order['firstName'])) - $contactName['firstName'] = self::fromJSON($order['firstName']); - if (isset($order['lastName'])) - $contactName['lastName'] = self::fromJSON($order['lastName']); - if (isset($order['patronymic'])) - $contactName['patronymic'] = self::fromJSON($order['patronymic']); - - if (isset($contactName) && !empty($contactName)) - self::addOrderProperty($optionsOrderProps[$arFields['PERSON_TYPE_ID']]['fio'], - implode(" ", $contactName), $order['externalId']); - - /*foreach($order['items'] as $item) { - $p = CSaleBasket::GetList( - array('PRODUCT_ID' => 'ASC'), - array('ORDER_ID' => $order['externalId'], 'PRODUCT_ID' => $item['offer']['externalId']))->Fetch(); - - if(!$p) // if not found - continue; - - // del from basket - if(isset($item['deleted']) && $item['deleted']) { - CSaleBasket::Delete($p['ID']); - continue; - } - - // change existing basket items - if(!isset($item['offer']) && !$item['offer']['externalId']) - continue; - - $arProduct = array(); - - // create new - if(isset($item['created']) && $item['created']) { - $arProduct = array( - 'FUSER_ID' => $userId, - 'ORDER_ID' => $order['externalId'], - 'QUANTITY' => $item['quantity'], - 'CURRENCY' => $p['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' => $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'] - ); - - if (isset($item['initialPrice']) && $item['initialPrice']) - $arProduct['PRICE'] = (double) $item['initialPrice']; - - if (isset($item['discount']) && $item['discount']) { - $arProduct['PRICE'] = $arProduct['PRICE'] - (double) $item['disount']; - $arProduct['DISCOUNT_PRICE'] = $item['discount']; - } - - if (isset($item['discountPercent']) && $item['discountPercent']) { - //$arProducts['PRICE'] -- how ? - $arProduct['DISCOUNT_VALUE'] = $item['discountPercent']; - } - - if (isset($item['offer']['name']) && $item['offer']['name']) - $arProduct['NAME'] = $item['offer']['name']; - - CSaleBasket::Add($arProduct); - continue; - } - - // update old - if(isset($item['initialPrice']) && $item['initialPrice']) - $arProduct['PRICE'] = (double) $item['initialPrice']; - - if(isset($item['dicount']) && $item['discount']){ - $arProduct['PRICE'] = $arProducts['PRICE'] - (double) $item['disount']; - $arProduct['DISCOUNT_PRICE'] = $item['discount']; - } - - if(isset($item['discountPercent']) && $item['discountPercent']) { - //$arProducts['PRICE'] -- how ? - $arProduct['DISCOUNT_VALUE'] = $item['discountPercent']; - } - - if(isset($item['offer']['name']) && $item['offer']['name']) - $arProduct['NAME'] = $item['offer']['name']; - - CSaleBasket::Update($p['ID'], $arProduct); - }*/ - - // orderUpdate - $arFields = self::clearArr(array( - 'PRICE_DELIVERY' => $order['deliveryCost'], - 'PRICE' => $order['summ'], - 'DATE_MARKED' => $order['markDatetime'], - 'USER_ID' => $userId, //$order['customer'] - 'PAY_SYSTEM_ID' => $optionsPayTypes[$order['paymentType']], - 'PAYED' => $optionsPayment[$order['paymentStatus']], - //'PERSON_TYPE_ID' => $optionsOrderTypes[$order['orderType']], - 'DELIVERY_ID' => $optionsDelivTypes[$order['deliveryType']], - 'STATUS_ID' => $optionsPayStatuses[$order['status']], - 'REASON_CANCELED' => $order['statusComment'], - 'USER_DESCRIPTION' => $order['customerComment'], - 'COMMENTS' => $order['managerComment'] - )); - - $GLOBALS['INTARO_CRM_FROM_HISTORY'] = true; - - CSaleOrder::Update($order['externalId'], $arFields); - } - } - - return true; - } - - /** - * - * w+ event in bitrix log - */ - - public static function eventLog($auditType, $itemId, $description) { - - CEventLog::Add(array( - "SEVERITY" => "SECURITY", - "AUDIT_TYPE_ID" => $auditType, - "MODULE_ID" => self::$MODULE_ID, - "ITEM_ID" => $itemId, - "DESCRIPTION" => $description, - )); - } - - /** - * - * Agent function - * - * @return self name - */ - - public static function uploadOrdersAgent() { - self::uploadOrders(); - $failedIds = unserialize(COption::GetOptionString(self::$MODULE_ID, self::$CRM_ORDER_FAILED_IDS, 0)); - if(is_array($failedIds) && !empty($failedIds)) - self::uploadOrders(50, true); // upload failed orders - - return 'ICrmOrderActions::uploadOrdersAgent();'; - } - - /** - * - * Agent function - * - * @return self name - */ - - public static function orderHistoryAgent() { - self::orderHistory(); - return 'ICrmOrderActions::orderHistoryAgent();'; - } - - /** - * - * creates order or returns array of order and customer for mass upload - * - * @param type $orderId - * @param type $api - * @param type $arParams - * @param type $send - * @return boolean - * @return array - array('order' = $order, 'customer' => $customer) - */ - public static function orderCreate($arFields, $api, $arParams, $send = false) { - if(!$api || empty($arParams)) { // add cond to check $arParams - return false; - } - - if (empty($arFields)) { - //handle err - self::eventLog('ICrmOrderActions::orderCreate', 'empty($arFields)', 'incorrect order'); - - return false; - } - - $rsUser = CUser::GetByID($arFields['USER_ID']); - $arUser = $rsUser->Fetch(); - - $createdAt = new \DateTime($arUser['DATE_REGISTER']); - $createdAt = $createdAt->format('Y-m-d H:i:s'); - - // push customer (for crm) - $firstName = self::toJSON($arUser['NAME']); - $lastName = self::toJSON($arUser['LAST_NAME']); - $patronymic = self::toJSON($arUser['SECOND_NAME']); - - $phonePersonal = array( - 'number' => self::toJSON($arUser['PERSONAL_PHONE']), - 'type' => 'mobile' - ); - $phones[] = $phonePersonal; - - $phoneWork = array( - 'number' => self::toJSON($arUser['WORK_PHONE']), - 'type' => 'work' - ); - $phones[] = $phoneWork; - - $customer = self::clearArr(array( - 'externalId' => $arFields['USER_ID'], - 'lastName' => $lastName, - 'firstName' => $firstName, - 'patronymic' => $patronymic, - 'phones' => $phones, - 'createdAt' => $createdAt - )); - - if($send) - $customer = $api->customerEdit($customer); - - // error pushing customer - if (!$customer) { - //handle err - self::eventLog('ICrmOrderActions::orderCreate', 'IntaroCrm\RestApi::customerEdit', $api->getLastError()); - return false; - } - - // delivery types - $arId = array(); - if (strpos($arFields['DELIVERY_ID'], ":") !== false) - $arId = explode(":", $arFields["DELIVERY_ID"]); - - if ($arId) - $resultDeliveryTypeId = $arId[0]; - else - $resultDeliveryTypeId = $arFields['DELIVERY_ID']; - - - $resOrder = array(); - $resOrderDeliveryAddress = array(); - $contactNameArr = array(); - - $rsOrderProps = CSaleOrderPropsValue::GetList(array(), array('ORDER_ID' => $arFields['ID'])); - while ($ar = $rsOrderProps->Fetch()) { - switch ($ar['CODE']) { - case $arParams['optionsOrderProps'][$arFields['PERSON_TYPE_ID']]['index']: $resOrderDeliveryAddress['index'] = self::toJSON($ar['VALUE']); - break; - case 'CITY': $resOrderDeliveryAddress['city'] = self::toJSON($ar['VALUE']); - break; - case $arParams['optionsOrderProps'][$arFields['PERSON_TYPE_ID']]['text']: $resOrderDeliveryAddress['text'] = self::toJSON($ar['VALUE']); - break; - case 'LOCATION': if(!isset($resOrderDeliveryAddress['city']) && !$resOrderDeliveryAddress['city']) { - $resOrderDeliveryAddress['city'] = CSaleLocation::GetByID($ar['VALUE']); - $resOrderDeliveryAddress['city'] = self::toJSON($resOrderDeliveryAddress['city']['CITY_NAME_LANG']); - } - break; - case $arParams['optionsOrderProps'][$arFields['PERSON_TYPE_ID']]['fio']: $contactNameArr = self::explodeFIO($ar['VALUE']); - break; - case $arParams['optionsOrderProps'][$arFields['PERSON_TYPE_ID']]['phone']: $resOrder['phone'] = $ar['VALUE']; - break; - case $arParams['optionsOrderProps'][$arFields['PERSON_TYPE_ID']]['email']: $resOrder['email'] = $ar['VALUE']; - break; - } - - if (count($arParams['optionsOrderProps'][$arFields['PERSON_TYPE_ID']] > 4)) { - switch ($ar['CODE']) { - /*case $arParams['optionsOrderProps'][$arFields['PERSON_TYPE_ID']]['country']: $resOrderDeliveryAddress['country'] = self::toJSON($ar['VALUE']); - break; - case $arParams['optionsOrderProps'][$arFields['PERSON_TYPE_ID']]['region']: $resOrderDeliveryAddress['region'] = self::toJSON($ar['VALUE']); - break; - case $arParams['optionsOrderProps'][$arFields['PERSON_TYPE_ID']]['city']: $resOrderDeliveryAddress['city'] = self::toJSON($ar['VALUE']); - break; */ - case $arParams['optionsOrderProps'][$arFields['PERSON_TYPE_ID']]['street']: $resOrderDeliveryAddress['street'] = self::toJSON($ar['VALUE']); - break; - case $arParams['optionsOrderProps'][$arFields['PERSON_TYPE_ID']]['building']: $resOrderDeliveryAddress['building'] = self::toJSON($ar['VALUE']); - break; - case $arParams['optionsOrderProps'][$arFields['PERSON_TYPE_ID']]['flat']: $resOrderDeliveryAddress['flat'] = self::toJSON($ar['VALUE']); - break; - case $arParams['optionsOrderProps'][$arFields['PERSON_TYPE_ID']]['intercomcode']: $resOrderDeliveryAddress['intercomcode'] = self::toJSON($ar['VALUE']); - break; - case $arParams['optionsOrderProps'][$arFields['PERSON_TYPE_ID']]['floor']: $resOrderDeliveryAddress['floor'] = self::toJSON($ar['VALUE']); - break; - case $arParams['optionsOrderProps'][$arFields['PERSON_TYPE_ID']]['block']: $resOrderDeliveryAddress['block'] = self::toJSON($ar['VALUE']); - break; - case $arParams['optionsOrderProps'][$arFields['PERSON_TYPE_ID']]['house']: $resOrderDeliveryAddress['house'] = self::toJSON($ar['VALUE']); - break; - } - } - } - - $items = array(); - - $rsOrderBasket = CSaleBasket::GetList(array('PRODUCT_ID' => 'ASC'), array('ORDER_ID' => $arFields['ID'])); - while ($p = $rsOrderBasket->Fetch()) { - $pr = CCatalogProduct::GetList(array('ID' => $p['PRODUCT_ID']))->Fetch(); - if ($pr) - $pr = $pr['PURCHASING_PRICE']; - else - $pr = ''; - - if($p['DISCOUNT_VALUE']) - $p['DISCOUNT_PRICE'] = null; - - $items[] = array( - 'initialPrice' => (double) $p['PRICE'] + (double) $p['DISCOUNT_PRICE'], - 'purchasePrice' => $pr, - 'discount' => $p['DISCOUNT_PRICE'], - 'discountPercent' => $p['DISCOUNT_VALUE'], - 'quantity' => $p['QUANTITY'], - 'productId' => $p['PRODUCT_ID'], - 'productName' => self::toJSON($p['NAME']) - ); - } - - if($arFields['CANCELED'] == 'Y') - $arFields['STATUS_ID'] = $arFields['CANCELED']; - - $createdAt = new \DateTime($arFields['DATE_INSERT']); - $createdAt = $createdAt->format('Y-m-d H:i:s'); - - $resOrder = array( - 'number' => $arFields['ACCOUNT_NUMBER'], - 'phone' => $resOrder['phone'], - 'email' => $resOrder['email'], - 'deliveryCost' => $arFields['PRICE_DELIVERY'], - 'summ' => $arFields['PRICE'], - 'markDateTime' => $arFields['DATE_MARKED'], - 'externalId' => $arFields['ID'], - 'customerId' => $arFields['USER_ID'], - 'paymentType' => $arParams['optionsPayTypes'][$arFields['PAY_SYSTEM_ID']], - 'paymentStatus' => $arParams['optionsPayment'][$arFields['PAYED']], - 'orderType' => $arParams['optionsOrderTypes'][$arFields['PERSON_TYPE_ID']], - 'deliveryType' => $arParams['optionsDelivTypes'][$resultDeliveryTypeId], - 'status' => $arParams['optionsPayStatuses'][$arFields['STATUS_ID']], - 'statusComment' => $arFields['REASON_CANCELED'], - 'customerComment' => $arFields['USER_DESCRIPTION'], - 'managerComment' => $arFields['COMMENTS'], - 'createdAt' => $createdAt, - 'deliveryAddress' => $resOrderDeliveryAddress, - 'items' => $items - ); - - - if(isset($arParams['optionsSites']) && is_array($arParams['optionsSites']) - && in_array($arFields['LID'], $arParams['optionsSites'])) - $resOrder['site'] = $arFields['LID']; - - // parse fio - if(count($contactNameArr) == 1) { - $resOrder['firstName'] = $contactNameArr[0]; - } else { - $resOrder['lastName'] = $contactNameArr[0]; - $resOrder['firstName'] = $contactNameArr[1]; - $resOrder['patronymic'] = $contactNameArr[2]; - } - - $resOrder = self::clearArr($resOrder); - - if($send) - return $api->orderEdit($resOrder); - - return array( - 'order' => $resOrder, - 'customer' => $customer - ); - } - - /** - * removes all empty fields from arrays - * working with nested arrs - * - * @param type $arr - * @return boolean - */ - public static function clearArr($arr) { - if(!$arr || !is_array($arr)) - return false; - - foreach($arr as $key => $value) { - if(!$value || (is_array($value) && empty($value))) - unset($arr[$key]); - - if(is_array($value) && !empty($value)) - $arr[$key] = self::clearArr($value); - } - - return $arr; - } - - /** - * - * @global type $APPLICATION - * @param type $str in SITE_CHARSET - * @return type $str in utf-8 - */ - public static function toJSON($str) { - global $APPLICATION; - - return $APPLICATION->ConvertCharset($str, SITE_CHARSET, 'utf-8'); - } - - /** - * - * @global type $APPLICATION - * @param type $str in utf-8 - * @return type $str in SITE_CHARSET - */ - public static function fromJSON($str) { - global $APPLICATION; - - return $APPLICATION->ConvertCharset($str, 'utf-8', SITE_CHARSET); - } - - public static function explodeFIO($str) { - if(!$str) - return array(); - - $array = explode(" ", self::toJSON($str), 3); - $newArray = array(); - - foreach($array as $ar) { - if(!$ar) - continue; - - $newArray[] = $ar; - } - - return $newArray; - } - - public static function addOrderProperty($code, $value, $order) { - if (!$code) - return; - - if (!CModule::IncludeModule('sale')) - return; - - if ($arProp = CSaleOrderProps::GetList(array(), array('CODE' => $code))->Fetch()) { - return CSaleOrderPropsValue::Add(array( - 'NAME' => $arProp['NAME'], - 'CODE' => $arProp['CODE'], - 'ORDER_PROPS_ID' => $arProp['ID'], - 'ORDER_ID' => $order, - 'VALUE' => $value, - )); - } - } - - public static function getLocationCityId($cityName) { - if(!$cityName) - return; - - $dbLocation = CSaleLocation::GetList( - array( - "SORT" => "ASC", - "CITY_NAME_LANG" => "ASC" - ), - array("LID" => "ru", "CITY_NAME" => $cityName), false, false, array()); - - if($location = $dbLocation->Fetch()) - return $location['ID']; - } -} \ No newline at end of file diff --git a/intaro.intarocrm/classes/general/RestApi.php b/intaro.intarocrm/classes/general/RestApi.php deleted file mode 100644 index f4207900..00000000 --- a/intaro.intarocrm/classes/general/RestApi.php +++ /dev/null @@ -1,499 +0,0 @@ -apiUrl = $crmUrl.'/api/v'.$this->apiVersion.'/'; - $this->apiKey = $apiKey; - $this->parameters = array('apiKey' => $this->apiKey); - } - - - public function getStatusCode() - { - return $this->statusCode; - } - - /* Получение кода статуса и сообщения об ошибке */ - public function getLastError() - { - if (isset($this->response['errorMsg']) && isset($this->response['errors'])) - { - $result = $this->statusCode . ' ' . $this->response['errorMsg']; - foreach ($this->response['errors'] as $error) - $result .= ' ' . $error; - } - elseif (isset($this->response['errorMsg'])) - $result = $this->statusCode . ' ' . $this->response['errorMsg']; - else - $result = null; - return $result; - } - - /* Псообщения об ошибке */ - public function getLastErrorMessage() - { - return $this->response['errorMsg']; - } - - - /* Методы для работы с заказами */ - /** - * Получение заказа по id - * - * @param string $id - идентификатор заказа - * @param string $by - поиск заказа по id или externalId - * @return array - информация о заказе - */ - public function orderGet($id, $by = 'externalId') - { - $url = $this->apiUrl.'orders/'.$id; - - if ($by != 'externalId') - $this->parameters['by'] = $by; - $result = $this->curlRequest($url); - return $result; - } - - /** - * Создание заказа - * - * @param array $order- информация о заказе - * @return array - */ - public function orderCreate($order) - { - $dataJson = json_encode($order); - $this->parameters['order'] = $dataJson; - - $url = $this->apiUrl.'orders/create'; - $result = $this->curlRequest($url, 'POST'); - return $result; - } - - /** - * Изменение заказа - * - * @param array $order- информация о заказе - * @return array - */ - public function orderEdit($order) - { - $dataJson = json_encode($order); - $this->parameters['order'] = $dataJson; - - $url = $this->apiUrl.'orders/'.$order['externalId'].'/edit'; - $result = $this->curlRequest($url, 'POST'); - return $result; - } - - /** - * Пакетная загрузка заказов - * - * @param array $orders - массив заказов - * @return array - */ - public function orderUpload($orders) - { - $dataJson = json_encode($orders); - $this->parameters['orders'] = $dataJson; - - $url = $this->apiUrl.'orders/upload'; - $result = $this->curlRequest($url, 'POST'); - if (is_null($result) && isset($result['uploadedOrders'])) - return $result['uploadedOrders']; - return $result; - } - - /** - * Обновление externalId у заказов с переданными id - * - * @param array $orders- массив, содержащий id и externalId заказа - * @return array - */ - public function orderFixExternalIds($order) - { - $dataJson = json_encode($order); - $this->parameters['orders'] = $dataJson; - - $url = $this->apiUrl.'orders/fix-external-ids'; - $result = $this->curlRequest($url, 'POST'); - return $result; - } - - /** - * Удаление заказа - * - * @param string $id - идентификатор заказа - * @param string $by - поиск заказа по id или externalId - * @return array - */ - /* - public function orderDelete($id, $by = 'externalId') - { - $url = $this->apiUrl.'orders/'.$id.'/delete'; - if ($by != 'externalId') - $this->parameters['by'] = $by; - $result = $this->curlRequest($url, 'POST'); - return $result; - }*/ - - /** - * Получение последних измененных заказов - * - * @param DateTime $startDate - начальная дата выборки - * @param DateTime $endDate - конечная дата - * @param int $limit - ограничение на размер выборки - * @param int $offset - сдвиг - * @return array - массив заказов - */ - public function orderHistory($startDate = null, $endDate = null, $limit = 100, $offset = 0) - { - $url = $this->apiUrl.'orders/history'; - $this->parameters['startDate'] = $startDate; - $this->parameters['endDate'] = $endDate; - $this->parameters['limit'] = $limit; - $this->parameters['offset'] = $offset; - - $result = $this->curlRequest($url); - return $result; - } - - - /* Методы для работы с клиентами */ - /** - * Получение клиента по id - * - * @param string $id - идентификатор - * @param string $by - поиск заказа по id или externalId - * @return array - информация о клиенте - */ - public function customerGet($id, $by = 'externalId') - { - $url = $this->apiUrl.'customers/'.$id; - if ($by != 'externalId') - $this->parameters['by'] = $by; - $result = $this->curlRequest($url); - return $result; - } - - /** - * Создание клиента - * - * @param array $customer - информация о клиенте - * @return array - */ - public function customerCreate($customer) - { - $dataJson = json_encode($customer); - $this->parameters['customer'] = $dataJson; - - $url = $this->apiUrl.'customers/create'; - $result = $this->curlRequest($url, 'POST'); - return $result; - } - - /** - * Редактирование клиента - * - * @param array $customer - информация о клиенте - * @return array - */ - public function customerEdit($customer) - { - $dataJson = json_encode($customer); - $this->parameters['customer'] = $dataJson; - - $url = $this->apiUrl.'customers/'.$customer['externalId'].'/edit'; - $result = $this->curlRequest($url, 'POST'); - return $result; - } - - /** - * Пакетная загрузка клиентов - * - * @param array $customers - массив клиентов - * @return array - */ - public function customerUpload($customers) - { - $dataJson = json_encode($customers); - $this->parameters['customers'] = $dataJson; - - $url = $this->apiUrl.'customers/upload'; - $result = $this->curlRequest($url, 'POST'); - if (is_null($result) && isset($result['uploaded'])) - return $result['uploaded']; - return $result; - } - - /** - * Удаление клиента - * - * @param string $id - идентификатор - * @param string $by - поиск заказа по id или externalId - * @return array - */ - /* - public function customerDelete($id, $by = 'externalId') - { - $url = $this->apiUrl.'customers/'.$id.'/delete'; - if ($by != 'externalId') - $this->parameters['by'] = $by; - $result = $this->curlRequest($url, 'POST'); - return $result; - }*/ - - /** - * Получение списка заказов клиента - * - * @param string $id - идентификатор клиента - * @param string $by - поиск заказа по id или externalId - * @param DateTime $startDate - начальная дата выборки - * @param DateTime $endDate - конечная дата - * @param int $limit - ограничение на размер выборки - * @param int $offset - сдвиг - * @return array - массив заказов - */ - public function customerOrdersList($id, $startDate = null, $endDate = null, - $limit = 100, $offset = 0, $by = 'externalId') - { - $url = $this->apiUrl.'customers/'.$id.'/orders'; - if ($by != 'externalId') - $this->parameters['by'] = $by; - $this->parameters['startDate'] = $startDate; - $this->parameters['endDate'] = $endDate; - $this->parameters['limit'] = $limit; - $this->parameters['offset'] = $offset; - - $result = $this->curlRequest($url); - return $result; - } - - /* Методы для работы со справочниками */ - /** - * Получение списка типов доставки - * - * @return array - массив типов доставки - */ - public function deliveryTypesList() - { - $url = $this->apiUrl.'reference/delivery-types'; - $result = $this->curlRequest($url); - return $result; - } - - /** - * Редактирование типа доставки - * - * @param array $deliveryType - информация о типе доставки - * @return array - */ - public function deliveryTypeEdit($deliveryType) - { - $dataJson = json_encode($deliveryType); - $this->parameters['deliveryType'] = $dataJson; - - $url = $this->apiUrl.'reference/delivery-types/'.$deliveryType['code'].'/edit'; - $result = $this->curlRequest($url, 'POST'); - return $result; - } - - - /** - * Получение списка типов оплаты - * - * @return array - массив типов оплаты - */ - public function paymentTypesList() - { - $url = $this->apiUrl.'reference/payment-types'; - $result = $this->curlRequest($url); - return $result; - } - - /** - * Редактирование типа оплаты - * - * @param array $paymentType - информация о типе оплаты - * @return array - */ - public function paymentTypesEdit($paymentType) - { - $dataJson = json_encode($paymentType); - $this->parameters['paymentType'] = $dataJson; - - $url = $this->apiUrl.'reference/payment-types/'.$paymentType['code'].'/edit'; - $result = $this->curlRequest($url, 'POST'); - return $result; - } - - - /** - * Получение списка статусов оплаты - * - * @return array - массив статусов оплаты - */ - public function paymentStatusesList() - { - $url = $this->apiUrl.'reference/payment-statuses'; - $result = $this->curlRequest($url); - return $result; - } - - /** - * Редактирование статуса оплаты - * - * @param array $paymentStatus - информация о статусе оплаты - * @return array - */ - public function paymentStatusesEdit($paymentStatus) - { - $dataJson = json_encode($paymentStatus); - $this->parameters['paymentStatus'] = $dataJson; - - $url = $this->apiUrl.'reference/payment-statuses/'.$paymentStatus['code'].'/edit'; - $result = $this->curlRequest($url, 'POST'); - return $result; - } - - - /** - * Получение списка типов заказа - * - * @return array - массив типов заказа - */ - public function orderTypesList() - { - $url = $this->apiUrl.'reference/order-types'; - $result = $this->curlRequest($url); - return $result; - } - - /** - * Редактирование типа заказа - * - * @param array $orderType - информация о типе заказа - * @return array - */ - public function orderTypesEdit($orderType) - { - $dataJson = json_encode($orderType); - $this->parameters['orderType'] = $dataJson; - - $url = $this->apiUrl.'reference/order-types/'.$orderType['code'].'/edit'; - $result = $this->curlRequest($url, 'POST'); - return $result; - } - - /** - * Получение списка статусов заказа - * - * @return array - массив статусов заказа - */ - public function orderStatusesList() - { - $url = $this->apiUrl.'reference/statuses'; - $result = $this->curlRequest($url); - return $result; - } - - /** - * Редактирование статуса заказа - * - * @param array $status - информация о статусе заказа - * @return array - */ - public function orderStatusEdit($status) - { - $dataJson = json_encode($status); - $this->parameters['status'] = $dataJson; - - $url = $this->apiUrl.'reference/statuses/'.$status['code'].'/edit'; - $result = $this->curlRequest($url, 'POST'); - return $result; - } - - - /** - * Получение списка групп статусов заказа - * - * @return array - массив групп статусов заказа - */ - public function orderStatusGroupsList() - { - $url = $this->apiUrl.'reference/status-groups'; - $result = $this->curlRequest($url); - return $result; - } - - /** - * Обновление статистики - * - * @return array - статус вып обновления - */ - public function statisticUpdate() - { - $url = $this->apiUrl.'statistic/update'; - $result = $this->curlRequest($url); - return $result; - } - - protected function curlRequest($url, $method = 'GET', $format = 'json') - { - if ($method == 'GET' && !is_null($this->parameters)) - $url .= '?'.http_build_query($this->parameters); - - $ch = curl_init(); - curl_setopt($ch, CURLOPT_URL, $url); - curl_setopt($ch, CURLOPT_FAILONERROR, FALSE); - curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);// allow redirects - curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); // return into a variable - curl_setopt($ch, CURLOPT_TIMEOUT, 30); // times out after 30s - - if ($method == 'POST') - { - curl_setopt($ch, CURLOPT_POST, true); - curl_setopt($ch, CURLOPT_POSTFIELDS, $this->parameters); - } - - $response = curl_exec($ch); - $this->statusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE); - unset($this->parameters); - /* Сброс массива с параметрами */ - $this->parameters = array('apiKey' => $this->apiKey); - - if (curl_errno($ch)) - { - $this->response = array('errorMsg' => 'Curl error: ' . curl_error($ch)); - return null; - } - curl_close($ch); - - $result = (array)json_decode($response, true); - $this->response = $result; - if ($result['success'] == false) - return null; - - unset($result['success']); - if (count($result) == 0) - return true; - return reset($result); - } -} - -?> \ No newline at end of file diff --git a/intaro.intarocrm/classes/general/events/ICrmOrderEvent.php b/intaro.intarocrm/classes/general/events/ICrmOrderEvent.php deleted file mode 100644 index cead90e0..00000000 --- a/intaro.intarocrm/classes/general/events/ICrmOrderEvent.php +++ /dev/null @@ -1,251 +0,0 @@ - $optionsOrderTypes, - 'optionsDelivTypes' => $optionsDelivTypes, - 'optionsPayTypes' => $optionsPayTypes, - 'optionsPayStatuses' => $optionsPayStatuses, - 'optionsPayment' => $optionsPayment, - 'optionsOrderProps' => $optionsOrderProps - )); - - $arOrder = CSaleOrder::GetById($ID); - - if (is_array($arFields) && !empty($arFields)) { - $arFieldsNew = array( - 'USER_ID' => $arOrder['USER_ID'], - 'ID' => $ID, - 'PERSON_TYPE_ID' => $arOrder['PERSON_TYPE_ID'], - 'CANCELED' => $arOrder['CANCELED'], - 'STATUS_ID' => $arOrder['STATUS_ID'], - 'DATE_INSERT' => $arOrder['DATE_INSERT'], - 'LID' => $arOrder['LID'] - ); - - $arFieldsNew = array_merge($arFieldsNew, $arFields); - $arOrder = $arFieldsNew; - } - - $result = ICrmOrderActions::orderCreate($arOrder, $api, $arParams, true); - - if(!$result) { - ICrmOrderActions::eventLog('ICrmOrderEvent::writeDataOnOrderCreate', 'ICrmOrderActions::orderCreate', 'error during creating order'); - return false; - } - - return true; - } - - /** - * - * @param type $ID -- orderId - * @param type $cancel -- Y / N - cancel order status - * @param type $reason -- cancel reason - * @return boolean - */ - function onSaleCancelOrder($ID, $cancel, $reason) { - if(!$ID || !$cancel || ($cancel != 'Y')) - return true; - - if (!CModule::IncludeModule('iblock')) { - //handle err - ICrmOrderActions::eventLog('ICrmOrderEvent::onSaleCancelOrder', 'iblock', 'module not found'); - return true; - } - - if (!CModule::IncludeModule("sale")) { - //handle err - ICrmOrderActions::eventLog('ICrmOrderEvent::onSaleCancelOrder', 'sale', 'module not found'); - return true; - } - - if (!CModule::IncludeModule("catalog")) { - //handle err - ICrmOrderActions::eventLog('ICrmOrderEvent::onSaleCancelOrder', 'catalog', 'module not found'); - 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); - - //saved cat params - $optionsPayStatuses = unserialize(COption::GetOptionString(self::$MODULE_ID, self::$CRM_PAYMENT_STATUSES, 0)); // --statuses - - $api = new IntaroCrm\RestApi($api_host, $api_key); - - $order = array( - 'externalId' => (int) $ID, - 'status' => $optionsPayStatuses[$cancel], - 'statusComment' => ICrmOrderActions::toJSON($reason) - ); - - $api->orderEdit($order); - - // error pushing order - if ($api->getStatusCode() != 201) - ICrmOrderActions::eventLog('ICrmOrderEvent::onSaleCancelOrder', 'IntaroCrm\RestApi::orderEdit', $api->getLastError()); - - return true; - } - - /** - * - * @param type $ID -- orderId - * @param type $payed -- Y / N - pay order status - * @return boolean - */ - function onSalePayOrder($ID, $payed) { - if(!$ID || !$payed || ($payed != 'Y')) - return true; - - if (!CModule::IncludeModule('iblock')) { - //handle err - ICrmOrderActions::eventLog('ICrmOrderEvent::onSalePayOrder', 'iblock', 'module not found'); - return true; - } - - if (!CModule::IncludeModule("sale")) { - //handle err - ICrmOrderActions::eventLog('ICrmOrderEvent::onSalePayOrder', 'sale', 'module not found'); - return true; - } - - if (!CModule::IncludeModule("catalog")) { - //handle err - ICrmOrderActions::eventLog('ICrmOrderEvent::onSalePayOrder', 'catalog', 'module not found'); - 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); - - //saved cat params - $optionsPayment = unserialize(COption::GetOptionString(self::$MODULE_ID, self::$CRM_PAYMENT, 0)); - - $api = new IntaroCrm\RestApi($api_host, $api_key); - - $order = array( - 'externalId' => (int) $ID, - 'paymentStatus' => $optionsPayment[$payed] - ); - - $api->orderEdit($order); - - - // error pushing order - if ($api->getStatusCode() != 201) - ICrmOrderActions::eventLog('ICrmOrderEvent::onSalePayOrder', 'IntaroCrm\RestApi::orderEdit', $api->getLastError()); - - return true; - } -} \ No newline at end of file diff --git a/intaro.intarocrm/description.ru b/intaro.intarocrm/description.ru new file mode 100644 index 00000000..7573f5fe --- /dev/null +++ b/intaro.intarocrm/description.ru @@ -0,0 +1 @@ +* Изменен протокол передачи данных с http на https. \ No newline at end of file diff --git a/intaro.intarocrm/export/export_run.php b/intaro.intarocrm/export/export_run.php deleted file mode 100644 index 34b4f19b..00000000 --- a/intaro.intarocrm/export/export_run.php +++ /dev/null @@ -1,44 +0,0 @@ - "article", - "manufacturer" => "manufacturer", - "color" =>"color", - "weight" => "weight", - "size" => "size", - ); -$IBLOCK_PROPERTY_SKU = array(); -foreach ($iblockProperties as $prop) { - $skuProps = ('IBLOCK_PROPERTY_SKU' . "_" . $prop); - $skuProps = $$skuProps; - foreach ($skuProps as $iblock => $val) { - $IBLOCK_PROPERTY_SKU[$iblock][$prop] = $val; - } -} -$IBLOCK_PROPERTY_PRODUCT = array(); -foreach ($iblockProperties as $prop) { - $skuProps = "IBLOCK_PROPERTY_PRODUCT" . "_" . $prop; - $skuProps = $$skuProps; - foreach ($skuProps as $iblock => $val) { - $IBLOCK_PROPERTY_PRODUCT[$iblock][$prop] = $val; - } -} - - -$loader = new ICMLLoader(); -$loader->iblocks = $IBLOCK_EXPORT; -$loader->propertiesSKU = $IBLOCK_PROPERTY_SKU; -$loader->propertiesProduct = $IBLOCK_PROPERTY_PRODUCT; -$loader->filename = $SETUP_FILE_NAME; -$loader->application = $APPLICATION; -$loader->Load(); \ No newline at end of file diff --git a/intaro.intarocrm/export/export_setup.php b/intaro.intarocrm/export/export_setup.php deleted file mode 100644 index 8c4e8176..00000000 --- a/intaro.intarocrm/export/export_setup.php +++ /dev/null @@ -1,468 +0,0 @@ - "article", - "manufacturer" => "manufacturer", - "color" =>"color", - "weight" => "weight", - "size" => "size", - ); - -if(!check_bitrix_sessid()) return; - -__IncludeLang(GetLangFileName($_SERVER["DOCUMENT_ROOT"]."/bitrix/modules/intaro.intarocrm/lang/", "/icml_export_setup.php")); - -if (($ACTION == 'EXPORT' || $ACTION == 'EXPORT_EDIT' || $ACTION == 'EXPORT_COPY') && $STEP == 1) -{ - - - if (isset($arOldSetupVars['SETUP_FILE_NAME'])) - $SETUP_FILE_NAME = $arOldSetupVars['SETUP_FILE_NAME']; - if (isset($arOldSetupVars['SETUP_PROFILE_NAME'])) - $SETUP_PROFILE_NAME = $arOldSetupVars['SETUP_PROFILE_NAME']; - if (isset($arOldSetupVars['IBLOCK_EXPORT'])) - $IBLOCK_EXPORT = $arOldSetupVars['IBLOCK_EXPORT']; - - $IBLOCK_PROPERTY_SKU = array(); - foreach ($iblockProperties as $prop) { - foreach ($arOldSetupVars['IBLOCK_PROPERTY_SKU'. '_' . $prop] as $iblock => $val) { - $IBLOCK_PROPERTY_SKU[$iblock][$prop] = $val; - } - } - $IBLOCK_PROPERTY_PRODUCT = array(); - foreach ($iblockProperties as $prop) { - foreach ($arOldSetupVars['IBLOCK_PROPERTY_PRODUCT'. '_' . $prop] as $iblock => $val) { - $IBLOCK_PROPERTY_PRODUCT[$iblock][$prop] = $val; - } - } -} - - - -if ($STEP>1) -{ - - if (strlen($SETUP_FILE_NAME)<=0) - { - $arSetupErrors[] = GetMessage("CET_ERROR_NO_FILENAME"); - } - elseif ($APPLICATION->GetFileAccessPermission($SETUP_FILE_NAME) < "W") - { - $arSetupErrors[] = str_replace("#FILE#", $SETUP_FILE_NAME, GetMessage('CET_YAND_RUN_ERR_SETUP_FILE_ACCESS_DENIED')); - } - - if (($ACTION=="EXPORT_SETUP" || $ACTION == 'EXPORT_EDIT' || $ACTION == 'EXPORT_COPY') && strlen($SETUP_PROFILE_NAME)<=0) - { - $arSetupErrors[] = GetMessage("CET_ERROR_NO_PROFILE_NAME"); - } - - if (!empty($arSetupErrors)) - { - $STEP = 1; - } -} - -if (!empty($arSetupErrors)) - echo ShowError(implode('
', $arSetupErrors)); - - -if ($STEP==1) -{ - - -?> - - - -
- - -

-

- GetMessage("PROPERTY_ARTICLE_HEADER_NAME"), - "manufacturer" => GetMessage("PROPERTY_MANUFACTURER_HEADER_NAME"), - "color" => GetMessage("PROPERTY_COLOR_HEADER_NAME"), - "weight" => GetMessage("PROPERTY_WEIGHT_HEADER_NAME"), - "size" => GetMessage("PROPERTY_SIZE_HEADER_NAME"), - ); - - $iblockPropertiesHint = Array( - "article" => Array("ARTICLE", "ART", "ARTNUMBER", "ARTICUL", "ARTIKUL"), - "manufacturer" => Array("MANUFACTURER", "PROISVODITEL", "PROISVOD", "PROISV"), - "color" => Array("COLOR", "CVET"), - "weight" => Array("WEIGHT", "VES", "VEC"), - "size" => Array("SIZE", "RAZMER"), - ); - - - $boolAll = false; - $intCountChecked = 0; - $intCountAvailIBlock = 0; - $arIBlockList = array(); - $db_res = CIBlock::GetList(Array("IBLOCK_TYPE"=>"ASC", "NAME"=>"ASC"),array('CHECK_PERMISSIONS' => 'Y','MIN_PERMISSION' => 'W')); - while ($iblock = $db_res->Fetch()) - { - if ($arCatalog = CCatalog::GetByIDExt($iblock["ID"])) - { - if($arCatalog['CATALOG_TYPE'] == "D" || $arCatalog['CATALOG_TYPE'] == "X" || $arCatalog['CATALOG_TYPE'] == "P") - { - $propertiesSKU = null; - if ($arCatalog['CATALOG_TYPE'] == "X" || $arCatalog['CATALOG_TYPE'] == "P") - { - $iblockOffer = CCatalogSKU::GetInfoByProductIBlock($iblock["ID"]); - - $db_properties = CIBlock::GetProperties($iblockOffer['IBLOCK_ID'], Array()); - while($prop = $db_properties->Fetch()) - $propertiesSKU[] = $prop; - - $oldPropertySKU = null; - if (isset($IBLOCK_PROPERTY_SKU[$iblock['ID']])) { - foreach ($iblockPropertiesName as $key => $prop) { - $oldPropertySKU[$key] = $IBLOCK_PROPERTY_SKU[$iblock['ID']][$key]; - } - } - } - - - $propertiesProduct = null; - $db_properties = CIBlock::GetProperties($iblock['ID'], Array()); - while($prop = $db_properties->Fetch()) - $propertiesProduct[] = $prop; - - $oldPropertyProduct = null; - if (isset($IBLOCK_PROPERTY_PRODUCT[$iblock['ID']])) { - foreach ($iblockPropertiesName as $key => $prop) { - $oldPropertyProduct[$key] = $IBLOCK_PROPERTY_PRODUCT[$iblock['ID']][$key]; - } - } - - $arSiteList = array(); - $rsSites = CIBlock::GetSite($iblock["ID"]); - while ($arSite = $rsSites->Fetch()) - { - $arSiteList[] = $arSite["SITE_ID"]; - } - - if (count($IBLOCK_EXPORT) != 0) - $boolExport = (in_array($iblock['ID'], $IBLOCK_EXPORT)); - else - $boolExport = true; - - - $arIBlockList[] = array( - 'ID' => $iblock['ID'], - 'NAME' => $iblock['NAME'], - 'IBLOCK_TYPE_ID' => $iblock['IBLOCK_TYPE_ID'], - 'IBLOCK_EXPORT' => $boolExport, - 'PROPERTIES_SKU' => $propertiesSKU, - 'PROPERTIES_PRODUCT' => $propertiesProduct, - 'OLD_PROPERTY_SKU_SELECT' => $oldPropertySKU, - 'OLD_PROPERTY_PRODUCT_SELECT' => $oldPropertyProduct, - 'SITE_LIST' => '('.implode(' ',$arSiteList).')', - ); - - if ($boolExport) - $intCountChecked++; - $intCountAvailIBlock++; - } - } - } - if (count($IBLOCK_EXPORT) != 0) { - if ($intCountChecked == $intCountAvailIBlock) - $boolAll = true; - } else { - $intCountChecked = $intCountAvailIBlock; - $boolAll = true; - } - - - - - ?> - - - > -
-
-
- - $arIBlock):?> -
-
- - ]" - id="IBLOCK_EXPORT" - value="" - - onclick="checkOne(this,);" - > -
-
-
- > - - - - - - - - - - - - $property): ?> - - - - - - - - - - -
-
-
-
-
-
-
- - - - - -
-
-
-
-
- - - -
- - -
- -

- -

- - -
-
-
- - - -

- -
-
-
- - - - - - - - - - - - - "> - - - - "> - - -
- - \ No newline at end of file diff --git a/intaro.intarocrm/include.php b/intaro.intarocrm/include.php deleted file mode 100755 index 933ef5fa..00000000 --- a/intaro.intarocrm/include.php +++ /dev/null @@ -1,10 +0,0 @@ - 'classes/general/RestApi.php', - 'ICrmOrderActions' => 'classes/general/ICrmOrderActions.php', - 'ICMLLoader' => 'classes/general/ICMLLoader.php', - 'ICrmOrderEvent' => 'classes/general/events/ICrmOrderEvent.php' - ) -); \ No newline at end of file diff --git a/intaro.intarocrm/install/export/intarocrm_run.php b/intaro.intarocrm/install/export/intarocrm_run.php deleted file mode 100644 index 35313159..00000000 --- a/intaro.intarocrm/install/export/intarocrm_run.php +++ /dev/null @@ -1,3 +0,0 @@ -IntaroCRM -require($_SERVER["DOCUMENT_ROOT"]."/bitrix/modules/intaro.intarocrm/export/export_run.php"); \ No newline at end of file diff --git a/intaro.intarocrm/install/export/intarocrm_setup.php b/intaro.intarocrm/install/export/intarocrm_setup.php deleted file mode 100644 index b2297fb0..00000000 --- a/intaro.intarocrm/install/export/intarocrm_setup.php +++ /dev/null @@ -1,3 +0,0 @@ -IntaroCRM -require($_SERVER["DOCUMENT_ROOT"]."/bitrix/modules/intaro.intarocrm/export/export_setup.php"); \ No newline at end of file diff --git a/intaro.intarocrm/install/index.php b/intaro.intarocrm/install/index.php index b587945a..8bb509be 100755 --- a/intaro.intarocrm/install/index.php +++ b/intaro.intarocrm/install/index.php @@ -440,6 +440,7 @@ class intaro_intarocrm extends CModule { // form correct url $api_host = parse_url($api_host); + if($api_host['scheme'] != 'https') $api_host['scheme'] = 'https'; $api_host = $api_host['scheme'] . '://' . $api_host['host']; if (!$api_host || !$api_key) { @@ -822,34 +823,21 @@ class intaro_intarocrm extends CModule { $arResult['errCode'] = 'ERR_FIELDS_IBLOCK'; else $iblocks = $_POST['IBLOCK_EXPORT']; - - $iblockProperties = Array( - "article" => "article", - "manufacturer" => "manufacturer", - "color" =>"color", - "weight" => "weight", - "size" => "size", - ); - - $propertiesSKU = array(); - foreach ($iblockProperties as $prop) { - foreach ($_POST['IBLOCK_PROPERTY_SKU'. '_' . $prop] as $iblock => $val) { - $propertiesSKU[$iblock][$prop] = $val; - } - } - - $propertiesProduct = array(); - foreach ($iblockProperties as $prop) { - foreach ($_POST['IBLOCK_PROPERTY_PRODUCT'. '_' . $prop] as $iblock => $val) { - $propertiesProduct[$iblock][$prop] = $val; - } - } + + if (!isset($_POST['IBLOCK_PROPERTY_ARTICLE'])) + $arResult['errCode'] = 'ERR_FIELDS_ARTICLE'; + else + $articleProperties = $_POST['IBLOCK_PROPERTY_ARTICLE']; if (!isset($_POST['SETUP_FILE_NAME'])) $arResult['errCode'] = 'ERR_FIELDS_FILE'; else $filename = $_POST['SETUP_FILE_NAME']; - + + if (count($iblocks) < count($articleProperties)) + $arResult['errCode'] = 'ERR_ARTICLE_IBLOCK'; + + if (!isset($_POST['TYPE_LOADING'])) $typeLoading = 0; else @@ -870,16 +858,15 @@ class intaro_intarocrm extends CModule { $arOldValues = Array( 'IBLOCK_EXPORT' => $iblocks, - 'IBLOCK_PROPERTY_SKU' => $propertiesSKU, - 'IBLOCK_PROPERTY_PRODUCT' => $propertiesProduct, + 'IBLOCK_PROPERTY_ARTICLE' => $articleProperties, 'SETUP_FILE_NAME' => $filename, 'SETUP_PROFILE_NAME' => $profileName ); global $oldValues; $oldValues = $arOldValues; $APPLICATION->IncludeAdminFile( - GetMessage('MODULE_INSTALL_TITLE'), - $_SERVER['DOCUMENT_ROOT'] . '/bitrix/modules/' . $this->MODULE_ID . '/install/step4.php' + GetMessage('MODULE_INSTALL_TITLE'), + $_SERVER['DOCUMENT_ROOT'] . '/bitrix/modules/' . $this->MODULE_ID . '/install/step5.php' ); return; } @@ -892,14 +879,12 @@ class intaro_intarocrm extends CModule { $loader = new ICMLLoader(); $loader->iblocks = $iblocks; - $loader->propertiesProduct = $propertiesProduct; - $loader->propertiesSKU = $propertiesSKU; + $loader->articleProperties = $articleProperties; $loader->filename = $filename; $loader->application = $APPLICATION; $loader->Load(); - - } - + } + if ($typeLoading == 'agent' || $typeLoading == 'cron') { if (file_exists($_SERVER['DOCUMENT_ROOT'] . '/bitrix/php_interface/include/catalog_export/' . $this->INTARO_CRM_EXPORT . '_run.php')) { $dbProfile = CCatalogExport::GetList(array(), array("FILE_NAME" => $this->INTARO_CRM_EXPORT)); @@ -911,18 +896,18 @@ class intaro_intarocrm extends CModule { } } } - $ar = $this->GetProfileSetupVars($iblocks, $propertiesProduct, $propertiesSKU, $filename); + $ar = $this->GetProfileSetupVars($iblocks, $articleProperties, $filename); $PROFILE_ID = CCatalogExport::Add(array( - "LAST_USE" => false, - "FILE_NAME" => $this->INTARO_CRM_EXPORT, - "NAME" => $profileName, - "DEFAULT_PROFILE" => "N", - "IN_MENU" => "N", - "IN_AGENT" => "N", - "IN_CRON" => "N", - "NEED_EDIT" => "N", - "SETUP_VARS" => $ar - )); + "LAST_USE" => false, + "FILE_NAME" => $this->INTARO_CRM_EXPORT, + "NAME" => $profileName, + "DEFAULT_PROFILE" => "N", + "IN_MENU" => "N", + "IN_AGENT" => "N", + "IN_CRON" => "N", + "NEED_EDIT" => "N", + "SETUP_VARS" => $ar + )); if (intval($PROFILE_ID) <= 0) { $arResult['errCode'] = 'ERR_IBLOCK'; return; @@ -1090,26 +1075,22 @@ class intaro_intarocrm extends CModule { unlink($_SERVER['DOCUMENT_ROOT'] . '/bitrix/php_interface/include/catalog_export/intarocrm_setup.php'); } - function GetProfileSetupVars($iblocks, $propertiesProduct, $propertiesSKU, $filename) { + function GetProfileSetupVars($iblocks, $articleProperties, $filename) { // Get string like IBLOCK_EXPORT[0]=3& // IBLOCK_EXPORT[1]=6& // IBLOCK_PROPERTY_ARTICLE[0]=ARTICLE& // IBLOCK_PROPERTY_ARTICLE[1]=ARTNUMBER& // SETUP_FILE_NAME=%2Fbitrix%2Fcatalog_export%2Ftestintarocrm.xml - //$arProfileFields = explode(",", $SETUP_FIELDS_LIST); $strVars = ""; - foreach ($iblocks as $key => $val) + foreach ($iblocks as $key => $val) $strVars .= 'IBLOCK_EXPORT[' . $key . ']=' . $val . '&'; - foreach ($propertiesSKU as $iblock => $arr) - foreach ($arr as $id => $val) - $strVars .= 'IBLOCK_PROPERTY_SKU_' . $id . '[' . $iblock . ']=' . $val . '&'; - foreach ($propertiesProduct as $iblock => $arr) - foreach ($arr as $id => $val) - $strVars .= 'IBLOCK_PROPERTY_PRODUCT_' . $id . '[' . $iblock . ']=' . $val . '&'; - + foreach ($articleProperties as $key => $val) + $strVars .= 'IBLOCK_PROPERTY_ARTICLE[' . $key . ']=' . $val . '&'; + $strVars .= 'SETUP_FILE_NAME=' . urlencode($filename); - + return $strVars; } + } \ No newline at end of file diff --git a/intaro.intarocrm/install/step1.php b/intaro.intarocrm/install/step1.php deleted file mode 100755 index 587334c1..00000000 --- a/intaro.intarocrm/install/step1.php +++ /dev/null @@ -1,62 +0,0 @@ - - -
-
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
- -
 
-
-
-
- " class="adm-btn-save"> -
-
-
-
\ No newline at end of file diff --git a/intaro.intarocrm/install/step2.php b/intaro.intarocrm/install/step2.php deleted file mode 100755 index 1e8e78a7..00000000 --- a/intaro.intarocrm/install/step2.php +++ /dev/null @@ -1,260 +0,0 @@ - 'eshop-individual', - 2 => 'eshop-legal' -); - -$defaultDelivTypes = array ( - 1 => 'courier', - 2 => 'self-delivery' -); - -$defaultPayTypes = array ( - 1 => 'cash', - 5 => 'bank-transfer', - 6 => 'bank-transfer' -); - -$defaultPayStatuses = array ( - 'N' => 'new', - 'P' => 'approval', - 'F' => 'complete', - 'Y' => 'cancel-other' -); - -$defaultPayment = array( - 'Y' => 'paid', - 'N' => 'not-paid' -); - -?> - - - - - - -
-
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
- - -
" . GetMessage('URL_1') . "" . " " . 'IntaroCRM.'; ?>
- - - -
- - - -
- - - -
- - - -
- - - -
-
-
-
- " class="adm-btn-save"> -
-
- " class="adm-btn-save"> -
-
-
-
\ No newline at end of file diff --git a/intaro.intarocrm/install/step3.php b/intaro.intarocrm/install/step3.php deleted file mode 100755 index 81668f47..00000000 --- a/intaro.intarocrm/install/step3.php +++ /dev/null @@ -1,103 +0,0 @@ - array( - 'fio' => 'FIO', - 'index' => 'ZIP', - 'text' => 'ADDRESS', - 'phone' => 'PHONE', - 'email' => 'EMAIL' - ), - 2 => array( - 'fio' => 'FIO', - 'index' => 'ZIP', - 'text' => 'ADDRESS', - 'phone' => 'PHONE', - 'email' => 'EMAIL' - ) -); - -?> - - - -
-
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - 4) echo 'class="address-detail-' . $bitrixOrderType['ID'] . '"'; if(($countProps > 4) && (count($defaultOrderProps[$bitrixOrderType['ID']]) < 6)) echo 'style="display:none;"';?>> - - - - - - -
- - - - -
- ConvertCharset($orderProp['NAME'], 'utf-8', SITE_CHARSET);; ?> - - -
-
-
-
- " class="adm-btn-save"> -
-
- " class="adm-btn-save"> -
-
-
-
\ No newline at end of file diff --git a/intaro.intarocrm/install/step4.php b/intaro.intarocrm/install/step4.php deleted file mode 100644 index e10d025b..00000000 --- a/intaro.intarocrm/install/step4.php +++ /dev/null @@ -1,203 +0,0 @@ - - - - - - - -
- - - - - - -
- - - - - - -
-
-
-
-
-
-
0%
-
- 0% -
-
-
-
-
-
- " class="adm-btn-save"> -
-
- " class="adm-btn-save"> -
-
-
-
\ No newline at end of file diff --git a/intaro.intarocrm/install/step5.php b/intaro.intarocrm/install/step5.php deleted file mode 100644 index 9378847a..00000000 --- a/intaro.intarocrm/install/step5.php +++ /dev/null @@ -1,405 +0,0 @@ - -

- - - - - -
-

-

- GetMessage("PROPERTY_ARTICLE_HEADER_NAME"), - "manufacturer" => GetMessage("PROPERTY_MANUFACTURER_HEADER_NAME"), - "color" => GetMessage("PROPERTY_COLOR_HEADER_NAME"), - "weight" => GetMessage("PROPERTY_WEIGHT_HEADER_NAME"), - "size" => GetMessage("PROPERTY_SIZE_HEADER_NAME"), - ); - - $iblockPropertiesHint = Array( - "article" => Array("ARTICLE", "ART", "ARTNUMBER", "ARTICUL", "ARTIKUL"), - "manufacturer" => Array("MANUFACTURER", "PROISVODITEL", "PROISVOD", "PROISV"), - "color" => Array("COLOR", "CVET"), - "weight" => Array("WEIGHT", "VES", "VEC"), - "size" => Array("SIZE", "RAZMER"), - ); - - - $boolAll = false; - $intCountChecked = 0; - $intCountAvailIBlock = 0; - $arIBlockList = array(); - $db_res = CIBlock::GetList(Array("IBLOCK_TYPE"=>"ASC", "NAME"=>"ASC"),array('CHECK_PERMISSIONS' => 'Y','MIN_PERMISSION' => 'W')); - while ($iblock = $db_res->Fetch()) - { - if ($arCatalog = CCatalog::GetByIDExt($iblock["ID"])) - { - if($arCatalog['CATALOG_TYPE'] == "D" || $arCatalog['CATALOG_TYPE'] == "X" || $arCatalog['CATALOG_TYPE'] == "P") - { - $propertiesSKU = null; - if ($arCatalog['CATALOG_TYPE'] == "X" || $arCatalog['CATALOG_TYPE'] == "P") - { - $iblockOffer = CCatalogSKU::GetInfoByProductIBlock($iblock["ID"]); - - $db_properties = CIBlock::GetProperties($iblockOffer['IBLOCK_ID'], Array()); - while($prop = $db_properties->Fetch()) - $propertiesSKU[] = $prop; - - $oldPropertySKU = null; - if (isset($IBLOCK_PROPERTY_SKU[$iblock['ID']])) { - foreach ($iblockPropertiesName as $key => $prop) { - $oldPropertySKU[$key] = $IBLOCK_PROPERTY_SKU[$iblock['ID']][$key]; - } - } - } - - - $propertiesProduct = null; - $db_properties = CIBlock::GetProperties($iblock['ID'], Array()); - while($prop = $db_properties->Fetch()) - $propertiesProduct[] = $prop; - - $oldPropertyProduct = null; - if (isset($IBLOCK_PROPERTY_PRODUCT[$iblock['ID']])) { - foreach ($iblockPropertiesName as $key => $prop) { - $oldPropertyProduct[$key] = $IBLOCK_PROPERTY_PRODUCT[$iblock['ID']][$key]; - } - } - - $arSiteList = array(); - $rsSites = CIBlock::GetSite($iblock["ID"]); - while ($arSite = $rsSites->Fetch()) - { - $arSiteList[] = $arSite["SITE_ID"]; - } - - if (count($IBLOCK_EXPORT) != 0) - $boolExport = (in_array($iblock['ID'], $IBLOCK_EXPORT)); - else - $boolExport = true; - - - $arIBlockList[] = array( - 'ID' => $iblock['ID'], - 'NAME' => $iblock['NAME'], - 'IBLOCK_TYPE_ID' => $iblock['IBLOCK_TYPE_ID'], - 'IBLOCK_EXPORT' => $boolExport, - 'PROPERTIES_SKU' => $propertiesSKU, - 'PROPERTIES_PRODUCT' => $propertiesProduct, - 'OLD_PROPERTY_SKU_SELECT' => $oldPropertySKU, - 'OLD_PROPERTY_PRODUCT_SELECT' => $oldPropertyProduct, - 'SITE_LIST' => '('.implode(' ',$arSiteList).')', - ); - - if ($boolExport) - $intCountChecked++; - $intCountAvailIBlock++; - } - } - } - if (count($IBLOCK_EXPORT) != 0) { - if ($intCountChecked == $intCountAvailIBlock) - $boolAll = true; - } else { - $intCountChecked = $intCountAvailIBlock; - $boolAll = true; - } - - ?> - - - > -
-
-
- - $arIBlock):?> -
-
- - ]" - id="IBLOCK_EXPORT" - value="" - - onclick="checkOne(this,);" - > -
-
-
- > - - - - - - - - - - - - $property): ?> - - - - - - - - - - -
-
-
-
-
-
-
- - - - - -
-
-
-
-
- - - -
- - -
- - -

- - -
-
-
- -

-
-
-
-
-
-   - -
-
-
- -
-   - " - size="30"> -
-
-
-
- - - - - - - - - - - - - -
-
- " class="adm-btn-save"> -
-
- " class="adm-btn-save"> -
-
-
- - diff --git a/intaro.intarocrm/install/step6.php b/intaro.intarocrm/install/step6.php deleted file mode 100644 index 0f8fd95c..00000000 --- a/intaro.intarocrm/install/step6.php +++ /dev/null @@ -1,11 +0,0 @@ - - -
- - - - "> - diff --git a/intaro.intarocrm/install/unstep1.php b/intaro.intarocrm/install/unstep1.php deleted file mode 100755 index 617f3988..00000000 --- a/intaro.intarocrm/install/unstep1.php +++ /dev/null @@ -1,8 +0,0 @@ - - - - - "> -
\ No newline at end of file diff --git a/intaro.intarocrm/install/version.php b/intaro.intarocrm/install/version.php deleted file mode 100755 index 3ef4e8e3..00000000 --- a/intaro.intarocrm/install/version.php +++ /dev/null @@ -1,6 +0,0 @@ - "0.4.1", - "VERSION_DATE" => "2013-09-24 18:52:00", -); - diff --git a/intaro.intarocrm/lang/ru/classes/general/ICMLLoader.php b/intaro.intarocrm/lang/ru/classes/general/ICMLLoader.php deleted file mode 100644 index e21acd04..00000000 --- a/intaro.intarocrm/lang/ru/classes/general/ICMLLoader.php +++ /dev/null @@ -1,2 +0,0 @@ -http://partner.market.yandex.ru/legal/tt/"; -$MESS["YANDEX_PROPS_COMMON"] = "Общие настройки"; -$MESS["YANDEX_PROPS_TYPE"] = "Настройки типа описания"; -$MESS["YANDEX_PROPS_NO"] = "нет"; -$MESS["YANDEX_PROPS_ADDITIONAL"] = "Дополнительные свойства для выгрузки"; -$MESS["YANDEX_PROPS_ADDITIONAL_TITLE"] = "Выберите свойства"; -$MESS["YANDEX_PROPS_ADDITIONAL_MORE"] = "Еще"; -$MESS["YANDEX_PRICES"] = "Цены"; -$MESS["YANDEX_PRICE_TYPE"] = "Выводить цену"; -$MESS["YANDEX_PRICE_TYPE_NONE"] = "оптимальную"; -$MESS["YANDEX_CURRENCIES"] = "Валюты"; -$MESS["YANDEX_CURRENCY"] = "валюта"; -$MESS["YANDEX_CURRENCY_RATE"] = "курс"; -$MESS["YANDEX_CURRENCY_RATE_SITE"] = "сайт"; -$MESS["YANDEX_CURRENCY_RATE_CBRF"] = "Центральный банк РФ"; -$MESS["YANDEX_CURRENCY_RATE_NBU"] = "Национальный банк Украины"; -$MESS["YANDEX_CURRENCY_RATE_NBK"] = "Национальный банк Казахстана"; -$MESS["YANDEX_CURRENCY_RATE_CB"] = "банк своего региона"; -$MESS["YANDEX_CURRENCY_PLUS"] = "коррекция курса"; -$MESS["YANDEX_PARAMS_TITLE"] = "Свойство"; -$MESS["YANDEX_ERR_NO_ACCESS_IBLOCK_SKU"] = "Нет доступа к инфоблоку торговых предложений"; -$MESS["YANDEX_ERR_NO_IBLOCK_SKU_FOUND"] = "Инфоблок торговых предложений #ID# не найден"; -$MESS["YANDEX_ERR_NO_IBLOCK_FOUND_EXT"] = "Инфоблок #ID# не найден"; -$MESS["YANDEX_ERR_NO_IBLOCK_IS_CATALOG"] = "Инфоблок #ID# не является торговым каталогом и не имеет торговых предложений"; -$MESS["YANDEX_ERR_NO_SECTION_LIST"] = "Список разделов не задан"; -$MESS["YANDEX_ERR_FILE_ACCESS_DENIED"] = "Недостаточно прав для перезаписи файла #FILE#"; -$MESS["YANDEX_ERR_FILE_OPEN_WRITING"] = "Невозможно открыть файл #FILE# для записи"; -$MESS["YANDEX_ERR_SETUP_FILE_WRITE"] = "Запись в файл #FILE# невозможна"; -$MESS["YANDEX_PRODUCT_PROPS"] = "--- Инфоблок товаров ---"; -$MESS["YANDEX_OFFERS_PROPS"] = "--- Инфоблок торговых предложений ---"; -$MESS["YANDEX_SKU_SETTINGS"] = "Выгрузка торговых предложений"; -$MESS["YANDEX_OFFERS_SELECT"] = "Условие отбора"; -$MESS["YANDEX_SKU_EXPORT_ALL_TITLE"] = "Все предложения товара"; -$MESS["YANDEX_SKU_EXPORT_MIN_PRICE_TITLE"] = "Предложение с минимальной ценой"; -$MESS["YANDEX_SKU_EXPORT_PROP_TITLE"] = "Отбор по свойству"; -$MESS["YANDEX_SKU_EXPORT_PROP_ID"] = "Свойство"; -$MESS["YANDEX_SKU_EXPORT_PROP_COND"] = "Условие отбора"; -$MESS["YANDEX_SKU_EXPORT_PROP_VALUE"] = "Значения"; -$MESS["YANDEX_SKU_EXPORT_PROP_EMPTY"] = "--- выберите свойство ---"; -$MESS["YANDEX_SKU_EXPORT_PROP_SELECT_ZERO"] = "пусто"; -$MESS["YANDEX_SKU_EXPORT_PROP_SELECT_NONZERO"] = "не пусто"; -$MESS["YANDEX_SKU_EXPORT_PROP_SELECT_EQUAL"] = "равно"; -$MESS["YANDEX_SKU_EXPORT_PROP_SELECT_NONEQUAL"] = "не равно"; -$MESS["YANDEX_SKU_EXPORT_ERR_CONDITION_ABSENT"] = "Не указано, по какому принципу фильтровать экспортируемые торговые предложения"; -$MESS["YANDEX_SKU_EXPORT_ERR_PROPERTY_ABSENT"] = "Не указано свойство, по значению которого фильтруются торговые предложения"; -$MESS["YANDEX_SKU_EXPORT_ERR_PROPERTY_COND_ABSENT"] = "Не указано условие фильтрации торговых предложений по свойству"; -$MESS["YANDEX_SKU_EXPORT_ERR_PROPERTY_VALUES_ABSENT"] = "Не указаны значения свойств для фильтрации торговых предложений"; -$MESS["YANDEX_SAVE_ERR"] = "Ошибки сохранения"; -$MESS["YANDEX_ERR_BAD_PRICE_TYPE"] = "Задан неверный тип цен для выгрузки"; -$MESS["YANDEX_ERR_BAD_OFFERS_IBLOCK_ID"] = "Неверный ID инфоблока торговых предложений"; -$MESS["YANDEX_ERR_SKU_SETTINGS_ABSENT"] = "Отсутствуют настройки экспорта торговых предложений"; -$MESS["YANDEX_ROOT_DIRECTORY"] = "Основной раздел каталога"; -$MESS["CET_ERROR_IBLOCK_PERM"] = "Недостаточно прав для работы с инфоблоком ##IBLOCK_ID#"; -$MESS["CES_ERROR_BAD_EXPORT_FILENAME"] = "Имя файла экспорта содержит запрещенные символы"; \ No newline at end of file diff --git a/intaro.intarocrm/lang/ru/export_setup_templ.php b/intaro.intarocrm/lang/ru/export_setup_templ.php deleted file mode 100644 index 91f43fbc..00000000 --- a/intaro.intarocrm/lang/ru/export_setup_templ.php +++ /dev/null @@ -1,124 +0,0 @@ -Путь по умолчанию для экспортируемых файлов настроек модуля."; -$MESS["CAT_ADM_CSV_EXP_TAB1"] = "Инфоблок"; -$MESS["CAT_ADM_CSV_EXP_TAB1_TITLE"] = "Выбор информационного блока для экспорта"; -$MESS["CAT_ADM_CSV_EXP_TAB2"] = "Параметры экспорта"; -$MESS["CAT_ADM_CSV_EXP_TAB2_TITLE"] = "Настройка параметров экспорта"; -$MESS["CAT_ADM_CSV_EXP_TAB3"] = "Результат"; -$MESS["CAT_ADM_CSV_EXP_TAB3_TITLE"] = "Результат экспорта"; -$MESS["CAT_ADM_CSV_EXP_IBLOCK_ID"] = "Инфоблок"; -$MESS["CAT_ADM_CSV_EXP_ADD_SETTINGS"] = "Дополнительные настройки"; -$MESS["CAT_ADM_CSV_EXP_EXPORT_FILES"] = "Выгружать файлы"; -$MESS["CAT_ADM_CSV_EXP_TIME_STEP"] = "Время выполнения шага"; -$MESS["CAT_ADM_CSV_EXP_TIME_STEP_COMMENT"] = "0 - загрузить все сразу
положительное значение - число секунд на выполнение одного шага"; -$MESS["CAT_ADM_CSV_EXP_SEP_ELEMENTS"] = "Поля и свойства элементов"; -$MESS["CAT_ADM_CSV_EXP_SEP_SECTIONS"] = "Поля разделов"; -$MESS["CAT_ADM_CSV_EXP_SEP_SECTIONS_EXT"] = "Поля и пользовательские свойства разделов"; -$MESS["CAT_ADM_CSV_EXP_SEP_PRODUCT"] = "Свойства товара"; -$MESS["CAT_ADM_CSV_EXP_SEP_PRICES"] = "Цены"; -$MESS["CAT_ADM_CSV_EXP_SEP_SKU"] = "Поля и свойства торговых предложений"; -$MESS["CAT_ADM_CSV_EXP_DESCR_SECT_PROP"] = "Пользовательское свойство"; -$MESS["CAT_ADM_CSV_EXP_SECTION_LEVEL"] = "Раздел уровня #LEVEL#"; -$MESS["CATI_FI_PRICE_TYPE2"] = "Цена типа \"#TYPE#\""; -$MESS["CATI_FI_PRICE_TYPE3"] = "Цена типа \"#NAME#\" (#TYPE#)"; -$MESS["CATI_FI_PRICE_CURRENCY"] = "в валюте #CURRENCY#"; \ No newline at end of file diff --git a/intaro.intarocrm/lang/ru/icml_export_setup.php b/intaro.intarocrm/lang/ru/icml_export_setup.php deleted file mode 100644 index 7dc07010..00000000 --- a/intaro.intarocrm/lang/ru/icml_export_setup.php +++ /dev/null @@ -1,28 +0,0 @@ - \ No newline at end of file diff --git a/intaro.intarocrm/lang/ru/install/index.php b/intaro.intarocrm/lang/ru/install/index.php deleted file mode 100755 index a204a9dc..00000000 --- a/intaro.intarocrm/lang/ru/install/index.php +++ /dev/null @@ -1,34 +0,0 @@ -Дальнейшие действия

-

- Если вы произвели выгрузку заказов на шаге 3, то эти заказы уже доступны в вашей CRM и - через некоторое время по этим заказам будет подготовлены аналитические отчеты в Панели KPI. -

-

- Новые заказы будут отправляться агентом ICrmOrderActions::uploadOrdersAgent(); - в IntaroCRM каждые 10 минут (интервал можно изменить в разделе Агенты). -

-

- Если вы выбрали опцию «Выгрузить каталог сейчас» на шаге 4, то ваш каталог уже загружается в IntaroCRM. - Загрузка длится, как правило, не более 10 минут. Если вы не выбирали эту опцию, то генерацию файла с каталогом - можно произвести экспортом «IntaroCRM» в разделе Магазин > Настройки > Экспорт данных. - IntaroCRM проверяет и загружает данный файл с каталогом каждые 3 часа. -

-'; diff --git a/intaro.intarocrm/lang/ru/install/unstep1.php b/intaro.intarocrm/lang/ru/install/unstep1.php deleted file mode 100755 index 176e7982..00000000 --- a/intaro.intarocrm/lang/ru/install/unstep1.php +++ /dev/null @@ -1,3 +0,0 @@ - Интеграция).'; $MESS ['INFO_3'] = 'Код сайта в 1С-Битрикс должен совпадать с кодом сайта в IntaroCRM (Администрирование > Магазины).'; \ No newline at end of file diff --git a/intaro.intarocrm/options.php b/intaro.intarocrm/options.php index cb45c217..2764b779 100755 --- a/intaro.intarocrm/options.php +++ b/intaro.intarocrm/options.php @@ -96,6 +96,10 @@ if (isset($_POST['Update']) && ($_POST['Update'] == 'Y')) { $api_host = htmlspecialchars(trim($_POST['api_host'])); $api_key = htmlspecialchars(trim($_POST['api_key'])); + $api_host = parse_url($api_host); + if ($api_host['scheme'] != 'https') $api_host['scheme'] = 'https'; + $api_host = $api_host['scheme'] . '://' . $api_host['host']; + // if empty so select all? or exception --not obligatory $orderSites = array(); foreach ($_POST[$CRM_ORDER_SITES] as $site) { diff --git a/intaro.intarocrm/updater.php b/intaro.intarocrm/updater.php new file mode 100644 index 00000000..75047bea --- /dev/null +++ b/intaro.intarocrm/updater.php @@ -0,0 +1,9 @@ + Date: Tue, 8 Oct 2013 16:24:38 +0400 Subject: [PATCH 6/9] version file --- intaro.intarocrm/install/version.php | 5 +++++ 1 file changed, 5 insertions(+) create mode 100755 intaro.intarocrm/install/version.php diff --git a/intaro.intarocrm/install/version.php b/intaro.intarocrm/install/version.php new file mode 100755 index 00000000..7352b1b8 --- /dev/null +++ b/intaro.intarocrm/install/version.php @@ -0,0 +1,5 @@ + "0.4.2", + "VERSION_DATE" => "2013-10-04 18:18:00", +); \ No newline at end of file From eddf81659d6c4282634a9b6fe44a84ff0b4fee1c Mon Sep 17 00:00:00 2001 From: Grisha Pomadchin Date: Tue, 8 Oct 2013 17:07:55 +0400 Subject: [PATCH 7/9] revert to 494b5a270 --- intaro.intarocrm/description.ru | 1 - intaro.intarocrm/lang/ru/step1.php | 13 ------------- intaro.intarocrm/updater.php | 9 --------- 3 files changed, 23 deletions(-) delete mode 100644 intaro.intarocrm/description.ru delete mode 100755 intaro.intarocrm/lang/ru/step1.php delete mode 100644 intaro.intarocrm/updater.php diff --git a/intaro.intarocrm/description.ru b/intaro.intarocrm/description.ru deleted file mode 100644 index 7573f5fe..00000000 --- a/intaro.intarocrm/description.ru +++ /dev/null @@ -1 +0,0 @@ -* Изменен протокол передачи данных с http на https. \ No newline at end of file diff --git a/intaro.intarocrm/lang/ru/step1.php b/intaro.intarocrm/lang/ru/step1.php deleted file mode 100755 index 4746c48c..00000000 --- a/intaro.intarocrm/lang/ru/step1.php +++ /dev/null @@ -1,13 +0,0 @@ - Интеграция).'; -$MESS ['INFO_3'] = 'Код сайта в 1С-Битрикс должен совпадать с кодом сайта в IntaroCRM (Администрирование > Магазины).'; \ No newline at end of file diff --git a/intaro.intarocrm/updater.php b/intaro.intarocrm/updater.php deleted file mode 100644 index 75047bea..00000000 --- a/intaro.intarocrm/updater.php +++ /dev/null @@ -1,9 +0,0 @@ - Date: Wed, 9 Oct 2013 19:24:28 +0400 Subject: [PATCH 8/9] fix order history --- .../classes/general/ICrmOrderActions.php | 69 +++++++++++-------- 1 file changed, 41 insertions(+), 28 deletions(-) diff --git a/intaro.intarocrm/classes/general/ICrmOrderActions.php b/intaro.intarocrm/classes/general/ICrmOrderActions.php index 6c1f5438..00bcec65 100755 --- a/intaro.intarocrm/classes/general/ICrmOrderActions.php +++ b/intaro.intarocrm/classes/general/ICrmOrderActions.php @@ -298,22 +298,27 @@ class ICrmOrderActions $optionsOrderProps = unserialize(COption::GetOptionString(self::$MODULE_ID, self::$CRM_ORDER_PROPS, 0)); $api = new IntaroCrm\RestApi($api_host, $api_key); - + $dateStart = COption::GetOptionString(self::$MODULE_ID, self::$CRM_ORDER_HISTORY_DATE, null); + + var_dump($dateStart); $orderHistory = $api->orderHistory($dateStart); + + var_dump($orderHistory); if($dateStart) $dateStart = new \DateTime($dateStart); // pushing existing orders foreach ($orderHistory as $order) { - - // выбрасываем заказы от 'новых клиентов' - if(!isset($order['customer']) && !$order['customer']) - continue; - - if(!isset($order['externalId']) && !$order['externalId']) { + var_dump($order['externalId']); + + if(!isset($order['externalId']) && !$order['externalId']) { + + // we dont need new orders without any customers + if(!isset($order['customer']) && !$order['customer']) + continue; // new order $newOrderFields = array( @@ -336,7 +341,7 @@ class ICrmOrderActions $newOrderFields['ACCOUNT_NUMBER'] = $order['number']; $order['externalId'] = CSaleOrder::Add($newOrderFields); - + $api->orderFixExternalIds(array(array('id' => $order['id'], 'externalId' => $order['externalId']))); if ($api->getStatusCode() != 200) { @@ -492,8 +497,21 @@ class ICrmOrderActions self::addOrderProperty($optionsOrderProps[$arFields['PERSON_TYPE_ID']]['fio'], implode(" ", $contactName), $order['externalId']); - foreach($order['items'] as $item) { - if(!isset($item['offer']) && !$item['offer']['externalId']) + foreach($order['items'] as $item) { + var_dump($item); + // del from basket + if(isset($item['deleted']) && $item['deleted']) { + $p = CSaleBasket::GetList( + array('PRODUCT_ID' => 'ASC'), + array('ORDER_ID' => $order['externalId'], 'PRODUCT_ID' => $item['id']))->Fetch(); + + if($p) + CSaleBasket::Delete($p['ID']); + + continue; + } + + if(!isset($item['offer']) && !$item['offer']['externalId']) continue; $p = CSaleBasket::GetList( @@ -502,13 +520,7 @@ class ICrmOrderActions if(!$p) $p = CIBlockElement::GetByID($item['offer']['externalId'])->Fetch(); - - // del from basket - if(isset($item['deleted']) && $item['deleted']) { - CSaleBasket::Delete($p['ID']); - continue; - } - + // change existing basket items $arProduct = array(); @@ -552,8 +564,9 @@ class ICrmOrderActions if (isset($item['offer']['name']) && $item['offer']['name']) $arProduct['NAME'] = $item['offer']['name']; - //CSaleBasket::Add($arProduct); - + CSaleBasket::Add($arProduct); + continue; + } // update old @@ -561,7 +574,7 @@ class ICrmOrderActions $arProduct['PRICE'] = (double) $item['initialPrice']; if (isset($item['dicount']) && $item['discount']) { - $arProduct['PRICE'] = $arProducts['PRICE'] - (double) $item['disount']; + $arProduct['PRICE'] = $arProduct['PRICE'] - (double) $item['disount']; $arProduct['DISCOUNT_PRICE'] = $item['discount']; } @@ -570,18 +583,16 @@ class ICrmOrderActions $arProduct['DISCOUNT_VALUE'] = $item['discountPercent']; } + if (isset($item['quantity']) && $item['quantity']) + $arProduct['QUANTITY'] = $item['quantity']; + if (isset($item['offer']['name']) && $item['offer']['name']) $arProduct['NAME'] = $item['offer']['name']; CSaleBasket::Update($p['ID'], $arProduct); CSaleBasket::DeleteAll($userId); } - - $dateInsert = new \DateTime($arFields['DATE_INSERT']); - - if(!$dateStart || ($dateInsert > $dateStart)) - $dateStart = $dateInsert; - + // orderUpdate $arFields = self::clearArr(array( 'PRICE_DELIVERY' => $order['deliveryCost'], @@ -601,6 +612,8 @@ class ICrmOrderActions $GLOBALS['INTARO_CRM_FROM_HISTORY'] = true; CSaleOrder::Update($order['externalId'], $arFields); + + $dateStart = new \DateTime(); } } @@ -796,9 +809,9 @@ class ICrmOrderActions $p['DISCOUNT_PRICE'] = null; $items[] = array( - 'initialPrice' => (double) $p['PRICE'] + (double) $p['DISCOUNT_PRICE'], + 'initialPrice' => (double) $p['PRICE'] + (double) $p['DISCOUNT_PRICE'], 'purchasePrice' => $pr, - 'discount' => $p['DISCOUNT_PRICE'], + 'discount' => $p['DISCOUNT_PRICE'], 'discountPercent' => $p['DISCOUNT_VALUE'], 'quantity' => $p['QUANTITY'], 'productId' => $p['PRODUCT_ID'], From 3623a8e1340e02742f1564132db9622d6fb7b5f8 Mon Sep 17 00:00:00 2001 From: Grisha Pomadchin Date: Wed, 9 Oct 2013 19:29:07 +0400 Subject: [PATCH 9/9] order final fixes --- intaro.intarocrm/classes/general/ICrmOrderActions.php | 6 ------ intaro.intarocrm/options.php | 8 +++++--- 2 files changed, 5 insertions(+), 9 deletions(-) diff --git a/intaro.intarocrm/classes/general/ICrmOrderActions.php b/intaro.intarocrm/classes/general/ICrmOrderActions.php index 00bcec65..06749116 100755 --- a/intaro.intarocrm/classes/general/ICrmOrderActions.php +++ b/intaro.intarocrm/classes/general/ICrmOrderActions.php @@ -301,18 +301,13 @@ class ICrmOrderActions $dateStart = COption::GetOptionString(self::$MODULE_ID, self::$CRM_ORDER_HISTORY_DATE, null); - var_dump($dateStart); - $orderHistory = $api->orderHistory($dateStart); - - var_dump($orderHistory); if($dateStart) $dateStart = new \DateTime($dateStart); // pushing existing orders foreach ($orderHistory as $order) { - var_dump($order['externalId']); if(!isset($order['externalId']) && !$order['externalId']) { @@ -498,7 +493,6 @@ class ICrmOrderActions implode(" ", $contactName), $order['externalId']); foreach($order['items'] as $item) { - var_dump($item); // del from basket if(isset($item['deleted']) && $item['deleted']) { $p = CSaleBasket::GetList( diff --git a/intaro.intarocrm/options.php b/intaro.intarocrm/options.php index cb45c217..b5004e13 100755 --- a/intaro.intarocrm/options.php +++ b/intaro.intarocrm/options.php @@ -505,9 +505,11 @@ if (isset($_POST['Update']) && ($_POST['Update'] == 'Y')) { - + + +