From 212d922ab31193cca55b4826f18c15e442f0a54b Mon Sep 17 00:00:00 2001 From: Grisha Pomadchin Date: Mon, 8 Jul 2013 15:08:14 +0400 Subject: [PATCH 1/4] Changed api class, added opt fields, gen fixes. --- intaro.crm/classes/general/RestApi.php | 441 +++++++++++++++++++++++++ intaro.crm/include.php | 3 +- intaro.crm/install/index.php | 50 +-- intaro.crm/install/step2.php | 168 ++++++---- intaro.crm/install/version.php | 2 +- intaro.crm/lang/ru/install/step2.php | 7 +- intaro.crm/lang/ru/options.php | 8 +- intaro.crm/options.php | 186 +++++++---- 8 files changed, 696 insertions(+), 169 deletions(-) create mode 100644 intaro.crm/classes/general/RestApi.php diff --git a/intaro.crm/classes/general/RestApi.php b/intaro.crm/classes/general/RestApi.php new file mode 100644 index 00000000..cef13009 --- /dev/null +++ b/intaro.crm/classes/general/RestApi.php @@ -0,0 +1,441 @@ +apiUrl = $crmUrl.'/api/v'.$this->apiVersion.'/'; + $this->apiKey = $apiKey; + } + + + public function getStatusCode() + { + return $this->statusCode; + } + + /* Получение кода статуса и сообщения об ошибке */ + public function getLastError() + { + if (!is_null($this->lastError)) + return $this->statusCode . ' ' . $this->lastError; + else + return null; + } + + /* Псообщения об ошибке */ + public function getLastErrorMessage() + { + return $this->lastError; + } + + + /* Методы для работы с заказами */ + /** + * Получение заказа по id + * + * @param string $id - идентификатор заказа + * @return array - информация о заказе + */ + public function orderGet($id) + { + $url = $this->apiUrl.'orders/'.$id; + $result = $this->curlRequest($url); + return $result; + } + + /** + * Создание заказа + * + * @param array $order- информация о заказе + * @return array + */ + public function orderCreate($order) + { + $dataJson = json_encode($order); + $dataJson = str_replace(self::$jsonReplaceSource, self::$jsonReplaceTarget, + $dataJson); + $parameters = array(); + $parameters['order'] = $dataJson; + + $url = $this->apiUrl.'orders/create'; + $result = $this->curlRequest($url, $parameters, 'POST'); + return $result; + } + + /** + * Изменение заказа + * + * @param array $order- информация о заказе + * @return array + */ + public function orderEdit($order) + { + $dataJson = json_encode($order); + $dataJson = str_replace(self::$jsonReplaceSource, self::$jsonReplaceTarget, + $dataJson); + $parameters = array(); + $parameters['order'] = $dataJson; + + $url = $this->apiUrl.'orders/'.$order['id'].'/edit'; + $result = $this->curlRequest($url, $parameters, 'POST'); + return $result; + } + + /** + * Загрузка нескольких заказов + * + * @param array $orders - массив заказов + * @return array + */ + public function orderUpload($orders) + { + $dataJson = json_encode($orders); + $dataJson = str_replace(self::$jsonReplaceSource, self::$jsonReplaceTarget, + $dataJson); + $parameters = array(); + $parameters['orders'] = $dataJson; + + $url = $this->apiUrl.'orders/upload'; + $result = $this->curlRequest($url, $parameters, 'POST'); + return $result; + } + + /** + * Удаление заказа + * + * @param string $id - идентификатор заказа + * @return array + */ + public function orderDelete($id) + { + $url = $this->apiUrl.'orders/'.$id.'/delete'; + $result = $this->curlRequest($url, array(), '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'; + $parameters = array(); + $parameters['startDate'] = $startDate; + $parameters['endDate'] = $endDate; + $parameters['limit'] = $limit; + $parameters['offset'] = $offset; + + $result = $this->curlRequest($url, $parameters); + return $result; + } + + + /* Методы для работы с клиентами */ + /** + * Получение клиента по id + * + * @param string $id - идентификатор + * @return array - информация о клиенте + */ + public function customerGet($id) + { + $url = $this->apiUrl.'customers/'.$id; + $result = $this->curlRequest($url); + return $result; + } + + /** + * Создание клиента + * + * @param array $customer - информация о клиенте + * @return array + */ + public function customerCreate($customer) + { + $dataJson = json_encode($customer); + $dataJson = str_replace(self::$jsonReplaceSource, self::$jsonReplaceTarget, + $dataJson); + $parameters = array(); + $parameters['customer'] = $dataJson; + + $url = $this->apiUrl.'customers/create'; + $result = $this->curlRequest($url, $parameters, 'POST'); + return $result; + } + + /** + * Редактирование клиента + * + * @param array $customer - информация о клиенте + * @return array + */ + public function customerEdit($customer) + { + $dataJson = json_encode($customer); + $dataJson = str_replace(self::$jsonReplaceSource, self::$jsonReplaceTarget, + $dataJson); + $parameters = array(); + $parameters['customer'] = $dataJson; + + $url = $this->apiUrl.'customers/'.$customer['id'].'/edit'; + $result = $this->curlRequest($url, $parameters, 'POST'); + return $result; + } + + /** + * Удаление клиента + * + * @param string $id - идентификатор + * @return array + */ + public function customerDelete($id) + { + $url = $this->apiUrl.'customers/'.$id.'/delete'; + $result = $this->curlRequest($url, array(), 'POST'); + return $result; + } + + /** + * Получение списка заказов клиента + * + * @param string $id - идентификатор клиента + * @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) + { + $url = $this->apiUrl.'customers/'.$id.'/orders'; + $parameters = array(); + $parameters['startDate'] = $startDate; + $parameters['endDate'] = $endDate; + $parameters['limit'] = $limit; + $parameters['offset'] = $offset; + + $result = $this->curlRequest($url, $parameters); + 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); + $dataJson = str_replace(self::$jsonReplaceSource, self::$jsonReplaceTarget, + $dataJson); + $parameters = array(); + $parameters['deliveryType'] = $dataJson; + + $url = $this->apiUrl.'delivery-types/'.$deliveryType['code'].'/edit'; + $result = $this->curlRequest($url, $parameters, '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); + $dataJson = str_replace(self::$jsonReplaceSource, self::$jsonReplaceTarget, + $dataJson); + $parameters = array(); + $parameters['paymentType'] = $dataJson; + + $url = $this->apiUrl.'payment-types/'.$paymentType['code'].'/edit'; + $result = $this->curlRequest($url, $parameters, '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); + $dataJson = str_replace(self::$jsonReplaceSource, self::$jsonReplaceTarget, + $dataJson); + $parameters = array(); + $parameters['paymentStatus'] = $dataJson; + + $url = $this->apiUrl.'payment-statuses/'.$paymentStatus['code'].'/edit'; + $result = $this->curlRequest($url, $parameters, 'POST'); + return $result; + } + + + /** + * Получение списка типов заказа + * + * @return array - массив типов заказа + */ + public function orderTypesList() + { + $url = $this->apiUrl.'reference/order-types'; + $result = $this->curlRequest($url); + return $result; + } + + /** + * Редактирование типа заказа + * + * @param array $paymentType - информация о типе заказа + * @return array + */ + public function orderTypesEdit($orderType) + { + $dataJson = json_encode($orderType); + $dataJson = str_replace(self::$jsonReplaceSource, self::$jsonReplaceTarget, + $dataJson); + $parameters = array(); + $parameters['orderType'] = $dataJson; + + $url = $this->apiUrl.'order-types/'.$paymentType['code'].'/edit'; + $result = $this->curlRequest($url, $parameters, 'POST'); + return $result; + } + + + + + protected function curlRequest($url, $parameters = null, $method = 'GET', $format = 'json') + { + $parameters['apiKey'] = $this->apiKey; + + if ($method == 'GET' && !is_null($parameters)) + $url .= '?'.http_build_query($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, 3); // times out after 3s + + if ($method == 'POST') + { + curl_setopt($ch, CURLOPT_POST, true); + curl_setopt($ch, CURLOPT_POSTFIELDS, $parameters); + } + + $response = curl_exec($ch); + $this->statusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE); + + if (curl_errno($ch)) + { + $this->lastError = 'Curl error: ' . curl_error($ch); + return null; + } + curl_close($ch); + + $result = (array)json_decode($response, true); + if ($result['success'] == false) + { + $this->lastError = $result['errorMsg']; + return null; + } + + $this->lastError = null; + unset($result['success']); + if (count($result) == 0) + return true; + return reset($result); + } +} + +?> diff --git a/intaro.crm/include.php b/intaro.crm/include.php index 59995fc7..8acabe55 100644 --- a/intaro.crm/include.php +++ b/intaro.crm/include.php @@ -2,8 +2,7 @@ CModule::AddAutoloadClasses( 'intaro.crm', // module name array ( - 'IntaroCrmRestApi' => 'classes/general/IntaroCrmRestApi.php', - 'ICrmApi' => 'classes/general/ICrmApi.php' + 'IntaroCrm\RestApi' => 'classes/general/RestApi.php' ) ); ?> diff --git a/intaro.crm/install/index.php b/intaro.crm/install/index.php index b3394895..767dff67 100644 --- a/intaro.crm/install/index.php +++ b/intaro.crm/install/index.php @@ -28,6 +28,8 @@ class intaro_crm extends CModule var $CRM_DELIVERY_TYPES_ARR = 'deliv_types_arr'; var $CRM_PAYMENT_TYPES = 'pay_types_arr'; var $CRM_PAYMENT_STATUSES = 'pay_statuses_arr'; + var $CRM_PAYMENT = 'payment_arr'; //order payment Y/N + var $INSTALL_PATH; @@ -55,8 +57,8 @@ class intaro_crm extends CModule { global $APPLICATION, $step, $arResult; - include($this->INSTALL_PATH . '/../classes/general/ICrmApi.php'); - + include($this->INSTALL_PATH . '/../classes/general/RestApi.php'); + $step = intval($_REQUEST['step']); if ($step <= 1) { @@ -81,7 +83,7 @@ class intaro_crm extends CModule return; } - $this->INTARO_CRM_API = new ICrmApi($api_host, $api_key); + $this->INTARO_CRM_API = new \IntaroCrm\RestApi($api_host, $api_key); $this->INTARO_CRM_API->paymentStatusesList(); @@ -104,7 +106,8 @@ class intaro_crm extends CModule $arResult['orderTypesList'] = $this->INTARO_CRM_API->orderTypesList(); $arResult['deliveryTypesList'] = $this->INTARO_CRM_API->deliveryTypesList(); $arResult['paymentTypesList'] = $this->INTARO_CRM_API->paymentTypesList(); - $arResult['paymentStatusesList'] = $this->INTARO_CRM_API->paymentStatusesList(); + $arResult['paymentStatusesList'] = $this->INTARO_CRM_API->paymentStatusesList(); // --statuses + //$arResult['payment'] = $this->INTARO_CRM_API->getPymentsList() -- not exist //bitrix orderTypesList -- personTypes $dbOrderTypesList = CSalePersonType::GetList( @@ -163,7 +166,7 @@ class intaro_crm extends CModule } while ($arPaymentTypesList = $dbPaymentTypesList->Fetch()); } - //bitrix paymentStatusesList + //bitrix paymentStatusesList --statuses $dbPaymentStatusesList = CSaleStatus::GetList( array( "SORT" => "ASC", @@ -181,12 +184,12 @@ class intaro_crm extends CModule } while ($arPaymentStatusesList = $dbPaymentStatusesList->Fetch()); } - $APPLICATION->IncludeAdminFile( + $APPLICATION->IncludeAdminFile( GetMessage('MODULE_INSTALL_TITLE'), $_SERVER['DOCUMENT_ROOT'] . '/bitrix/modules/' . $this->MODULE_ID . '/install/step2.php' ); - } else if ($step == 3) { + } else if ($step == 3) { if(!CModule::IncludeModule("sale")) { //handler } @@ -206,14 +209,14 @@ class intaro_crm extends CModule ); //form order types ids arr - $orderTypesArr = array(); + $orderTypesArr = array(); if ($arOrderTypesList = $dbOrderTypesList->Fetch()) { do { - $orderTypesArr[$arOrderTypesList['ID']] = $_POST['order-type-' . $arOrderTypesList['ID']]; + $orderTypesArr[$arOrderTypesList['ID']] = htmlspecialchars(trim($_POST['order-type-' . $arOrderTypesList['ID']])); } while ($arOrderTypesList = $dbOrderTypesList->Fetch()); } - - //bitrix deliveryTypesList + + //bitrix deliveryTypesList $dbDeliveryTypesList = CSaleDelivery::GetList( array( "SORT" => "ASC", @@ -228,14 +231,14 @@ class intaro_crm extends CModule ); //form delivery types ids arr - $deliveryTypesArr = array(); + $deliveryTypesArr = array(); if ($arDeliveryTypesList = $dbDeliveryTypesList->Fetch()) { do { - $deliveryTypesArr[$arDeliveryTypesList['ID']] = $_POST['delivery-type-' . $arDeliveryTypesList['ID']]; + $deliveryTypesArr[$arDeliveryTypesList['ID']] = htmlspecialchars(trim($_POST['delivery-type-' . $arDeliveryTypesList['ID']])); } while ($arDeliveryTypesList = $dbDeliveryTypesList->Fetch()); } - //bitrix paymentTypesList + //bitrix paymentTypesList $dbPaymentTypesList = CSalePaySystem::GetList( array( "SORT" => "ASC", @@ -247,14 +250,14 @@ class intaro_crm extends CModule ); //form payment types ids arr - $paymentTypesArr = array(); + $paymentTypesArr = array(); if ($arPaymentTypesList = $dbPaymentTypesList->Fetch()) { do { - $paymentTypesArr[$arPaymentTypesList['ID']] = $_POST['payment-type-' . $arPaymentTypesList['ID']]; + $paymentTypesArr[$arPaymentTypesList['ID']] = htmlspecialchars(trim($_POST['payment-type-' . $arPaymentTypesList['ID']])); } while ($arPaymentTypesList = $dbPaymentTypesList->Fetch()); } - //bitrix paymentStatusesList + //bitrix paymentStatusesList $dbPaymentStatusesList = CSaleStatus::GetList( array( "SORT" => "ASC", @@ -270,14 +273,20 @@ class intaro_crm extends CModule $paymentStatusesArr = array(); if ($arPaymentStatusesList = $dbPaymentStatusesList->Fetch()) { do { - $paymentStatusesArr[$arPaymentStatusesList['ID']] = $_POST['payment-status-' . $arPaymentStatusesList['ID']]; + $paymentStatusesArr[$arPaymentStatusesList['ID']] = htmlspecialchars(trim($_POST['payment-status-' . $arPaymentStatusesList['ID']])); } while ($arPaymentStatusesList = $dbPaymentStatusesList->Fetch()); } + + //form payment ids arr + $paymentArr = array(); + $paymentArr['Y'] = htmlspecialchars(trim($_POST['payment-Y'])); + $paymentArr['N'] = htmlspecialchars(trim($_POST['payment-N'])); COption::SetOptionString($this->MODULE_ID, $this->CRM_ORDER_TYPES_ARR, serialize($orderTypesArr)); - COption::SetOptionString($this->MODULE_ID, $this->CRM_DELIVERY_TYPES_ARR, serialize($deliveryTypesArr)); + COption::SetOptionString($this->MODULE_ID, $this->CRM_DELIVERY_TYPES_ARR, serialize($deliveryTypesArr)); COption::SetOptionString($this->MODULE_ID, $this->CRM_PAYMENT_TYPES, serialize($paymentTypesArr)); COption::SetOptionString($this->MODULE_ID, $this->CRM_PAYMENT_STATUSES, serialize($paymentStatusesArr)); + COption::SetOptionString($this->MODULE_ID, $this->CRM_PAYMENT, serialize($paymentArr)); RegisterModule($this->MODULE_ID); $APPLICATION->IncludeAdminFile( @@ -297,11 +306,12 @@ class intaro_crm extends CModule COption::RemoveOption($this->MODULE_ID, $this->CRM_DELIVERY_TYPES_ARR); COption::RemoveOption($this->MODULE_ID, $this->CRM_PAYMENT_TYPES); COption::RemoveOption($this->MODULE_ID, $this->CRM_PAYMENT_STATUSES); + COption::RemoveOption($this->MODULE_ID, $this->CRM_PAYMENT); $APPLICATION->IncludeAdminFile( GetMessage('MODULE_UNINSTALL_TITLE'), $_SERVER['DOCUMENT_ROOT'] . '/bitrix/modules/' . $this->MODULE_ID . '/install/unstep1.php' - ); + ); } } ?> diff --git a/intaro.crm/install/step2.php b/intaro.crm/install/step2.php index cf99b677..32046691 100644 --- a/intaro.crm/install/step2.php +++ b/intaro.crm/install/step2.php @@ -1,4 +1,12 @@ - +
@@ -10,91 +18,111 @@ - - - - - - - - - - + + + + + + + + + - - - - - - - - - + + + + + + + + + - - - - - - - - - + + + + + + + + + + + + + + + + + + - - - - - - - - - + + + + + + + + + - - - -
- - -
+ + + -
- - -
+ + + -
- - -
+ + + +
+ + + -
- - -
+ + + -
+ + + + +
" class="adm-btn-save">
diff --git a/intaro.crm/install/version.php b/intaro.crm/install/version.php index b2a1360f..560d26eb 100644 --- a/intaro.crm/install/version.php +++ b/intaro.crm/install/version.php @@ -1,6 +1,6 @@ '0.2a', - 'VERSION_DATE' => '2013-07-05 21:08:00', + 'VERSION_DATE' => '2013-07-08 15:04:00', ); ?> diff --git a/intaro.crm/lang/ru/install/step2.php b/intaro.crm/lang/ru/install/step2.php index 895e1481..574d2360 100644 --- a/intaro.crm/lang/ru/install/step2.php +++ b/intaro.crm/lang/ru/install/step2.php @@ -3,6 +3,9 @@ $MESS ['STEP_NAME'] = 'Шаг 2'; $MESS ['MOD_NEXT_STEP'] = 'Следующий шаг'; $MESS ['DELIVERY_TYPES_LIST'] = 'Способы доставки'; $MESS ['PAYMENT_TYPES_LIST'] = 'Способы оплаты'; -$MESS ['PAYMENT_STATUS_LIST'] = 'Статусы оплаты'; -$MESS ['ORDER_TYPES_LIST'] = 'Типы плательщиков'; +$MESS ['PAYMENT_STATUS_LIST'] = 'Статусы'; +$MESS ['ORDER_TYPES_LIST'] = 'Типы заказа'; +$MESS ['PAYMENT_LIST'] = 'Оплата'; +$MESS ['PAYMENT_Y'] = 'Оплачен'; +$MESS ['PAYMENT_N'] = 'Не оплачен'; ?> diff --git a/intaro.crm/lang/ru/options.php b/intaro.crm/lang/ru/options.php index 698bcbe9..9c639de5 100644 --- a/intaro.crm/lang/ru/options.php +++ b/intaro.crm/lang/ru/options.php @@ -5,10 +5,14 @@ $MESS ['ICRM_CONN_SETTINGS'] = 'Настройка соединения'; $MESS ['ICRM_API_HOST'] = 'Адрес Intaro CRM:'; $MESS ['ICRM_API_KEY'] = 'Ключ авторизации:'; -$MESS ['ICRM_OPTIONS_CATALOG_TAB'] = 'Настройка каталогов'; +$MESS ['ICRM_OPTIONS_CATALOG_TAB'] = 'Настройка справочников'; $MESS ['DELIVERY_TYPES_LIST'] = 'Способы доставки'; $MESS ['PAYMENT_TYPES_LIST'] = 'Способы оплаты'; -$MESS ['PAYMENT_STATUS_LIST'] = 'Статусы оплаты'; +$MESS ['PAYMENT_STATUS_LIST'] = 'Статусы'; +$MESS ['ORDER_TYPES_LIST'] = 'Типы заказа'; +$MESS ['PAYMENT_LIST'] = 'Оплата'; +$MESS ['PAYMENT_Y'] = 'Оплачен'; +$MESS ['PAYMENT_N'] = 'Не оплачен'; $MESS ['ICRM_OPTIONS_SUBMIT_TITLE'] = 'Сохранить настройки'; $MESS ['ICRM_OPTIONS_SUBMIT_VALUE'] = 'Сохранить'; diff --git a/intaro.crm/options.php b/intaro.crm/options.php index 023f8c15..7ec8d250 100644 --- a/intaro.crm/options.php +++ b/intaro.crm/options.php @@ -3,6 +3,14 @@ IncludeModuleLangFile(__FILE__); $mid = 'intaro.crm'; $uri = $APPLICATION->GetCurPage() . '?mid=' . htmlspecialchars($mid) . '&lang=' . LANGUAGE_ID; +$CRM_API_HOST_OPTION = 'api_host'; +$CRM_API_KEY_OPTION = 'api_key'; +$CRM_ORDER_TYPES_ARR = 'order_types_arr'; +$CRM_DELIVERY_TYPES_ARR = 'deliv_types_arr'; +$CRM_PAYMENT_TYPES = 'pay_types_arr'; +$CRM_PAYMENT_STATUSES = 'pay_statuses_arr'; +$CRM_PAYMENT = 'payment_arr'; //order payment Y/N + CModule::IncludeModule('intaro.crm'); CModule::IncludeModule('sale'); @@ -20,7 +28,7 @@ if (isset($_POST['Update']) && $_POST['Update']=='Y') { $api_key = htmlspecialchars(trim($_POST['api_key'])); if($api_host && $api_key) { - $api = new ICrmApi($api_host, $api_key); + $api = new IntaroCrm\RestApi($api_host, $api_key); $api->paymentStatusesList(); @@ -49,7 +57,7 @@ if (isset($_POST['Update']) && $_POST['Update']=='Y') { ); //form order types ids arr - $orderTypesArr = array(); + $orderTypesArr = array(); if ($arOrderTypesList = $dbOrderTypesList->Fetch()) { do { $orderTypesArr[$arOrderTypesList['ID']] = $_POST['order-type-' . $arOrderTypesList['ID']]; @@ -68,73 +76,80 @@ if (isset($_POST['Update']) && $_POST['Update']=='Y') { false, false, array() - ); + ); - //form delivery types ids arr + //form delivery types ids arr $deliveryTypesArr = array(); - if ($arDeliveryTypesList = $dbDeliveryTypesList->Fetch()) { - do { - $deliveryTypesArr[$arDeliveryTypesList['ID']] = $_POST['delivery-type-' . $arDeliveryTypesList['ID']]; - } while ($arDeliveryTypesList = $dbDeliveryTypesList->Fetch()); - } + if ($arDeliveryTypesList = $dbDeliveryTypesList->Fetch()) { + do { + $deliveryTypesArr[$arDeliveryTypesList['ID']] = htmlspecialchars(trim($_POST['delivery-type-' . $arDeliveryTypesList['ID']])); + } while ($arDeliveryTypesList = $dbDeliveryTypesList->Fetch()); + } - //bitrix paymentTypesList - $dbPaymentTypesList = CSalePaySystem::GetList( - array( - "SORT" => "ASC", - "NAME" => "ASC" - ), - array( - "ACTIVE" => "Y" - ) - ); + //bitrix paymentTypesList + $dbPaymentTypesList = CSalePaySystem::GetList( + array( + "SORT" => "ASC", + "NAME" => "ASC" + ), + array( + "ACTIVE" => "Y" + ) + ); - //form payment types ids arr - $paymentTypesArr = array(); - if ($arPaymentTypesList = $dbPaymentTypesList->Fetch()) { - do { - $paymentTypesArr[$arPaymentTypesList['ID']] = $_POST['payment-type-' . $arPaymentTypesList['ID']]; - } while ($arPaymentTypesList = $dbPaymentTypesList->Fetch()); - } + //form payment types ids arr + $paymentTypesArr = array(); + if ($arPaymentTypesList = $dbPaymentTypesList->Fetch()) { + do { + $paymentTypesArr[$arPaymentTypesList['ID']] = htmlspecialchars(trim($_POST['payment-type-' . $arPaymentTypesList['ID']])); + } while ($arPaymentTypesList = $dbPaymentTypesList->Fetch()); + } - //bitrix paymentStatusesList - $dbPaymentStatusesList = CSaleStatus::GetList( - array( - "SORT" => "ASC", - "NAME" => "ASC" - ), - array( - "LID" => "ru", //ru - "ACTIVE" => "Y" + //bitrix paymentStatusesList + $dbPaymentStatusesList = CSaleStatus::GetList( + array( + "SORT" => "ASC", + "NAME" => "ASC" + ), + array( + "LID" => "ru", //ru + "ACTIVE" => "Y" ) - ); + ); - //form payment statuses ids arr - $paymentStatusesArr = array(); - if ($arPaymentStatusesList = $dbPaymentStatusesList->Fetch()) { - do { - $paymentStatusesArr[$arPaymentStatusesList['ID']] = $_POST['payment-status-' . $arPaymentStatusesList['ID']]; - } while ($arPaymentStatusesList = $dbPaymentStatusesList->Fetch()); - } - - COption::SetOptionString($mid, 'order_types_arr', serialize($orderTypesArr)); - COption::SetOptionString($mid, 'deliv_types_arr', serialize($deliveryTypesArr)); - COption::SetOptionString($mid, 'pay_types_arr', serialize($paymentTypesArr)); - COption::SetOptionString($mid, 'pay_statuses_arr', serialize($paymentStatusesArr)); + //form payment statuses ids arr + $paymentStatusesArr = array(); + if ($arPaymentStatusesList = $dbPaymentStatusesList->Fetch()) { + do { + $paymentStatusesArr[$arPaymentStatusesList['ID']] = htmlspecialchars(trim($_POST['payment-status-' . $arPaymentStatusesList['ID']])); + } while ($arPaymentStatusesList = $dbPaymentStatusesList->Fetch()); + } - $uri .= '&ok=Y'; - LocalRedirect($uri); + //form payment ids arr + $paymentArr = array(); + $paymentArr['Y'] = htmlspecialchars(trim($_POST['payment-Y'])); + $paymentArr['N'] = htmlspecialchars(trim($_POST['payment-N'])); + + COption::SetOptionString($mid, $CRM_ORDER_TYPES_ARR, serialize($orderTypesArr)); + COption::SetOptionString($mid, $CRM_DELIVERY_TYPES_ARR, serialize($deliveryTypesArr)); + COption::SetOptionString($mid, $CRM_PAYMENT_TYPES, serialize($paymentTypesArr)); + COption::SetOptionString($mid, $CRM_PAYMENT_STATUSES, serialize($paymentStatusesArr)); + COption::SetOptionString($mid, $CRM_PAYMENT, serialize($paymentArr)); + + $uri .= '&ok=Y'; + LocalRedirect($uri); } else { $api_host = COption::GetOptionString($mid, 'api_host', 0); $api_key = COption::GetOptionString($mid, 'api_key', 0); - $api = new ICrmApi($api_host, $api_key); + $api = new IntaroCrm\RestApi($api_host, $api_key); //prepare crm lists $arResult['orderTypesList'] = $api->orderTypesList(); $arResult['deliveryTypesList'] = $api->deliveryTypesList(); $arResult['paymentTypesList'] = $api->paymentTypesList(); - $arResult['paymentStatusesList'] = $api->paymentStatusesList(); + $arResult['paymentStatusesList'] = $api->paymentStatusesList(); // --statuses + //$arResult['payment'] = $this->INTARO_CRM_API->getPymentsList() -- not exist //bitrix orderTypesList -- personTypes $dbOrderTypesList = CSalePersonType::GetList( @@ -210,12 +225,19 @@ if (isset($_POST['Update']) && $_POST['Update']=='Y') { $arResult['bitrixPaymentStatusesList'][] = $arPaymentStatusesList; } while ($arPaymentStatusesList = $dbPaymentStatusesList->Fetch()); } + + //bitrix pyament Y/N + $arResult['bitrixPaymentList'][0]['NAME'] = GetMessage('PAYMENT_Y'); + $arResult['bitrixPaymentList'][0]['ID'] = 'Y'; + $arResult['bitrixPaymentList'][1]['NAME'] = GetMessage('PAYMENT_N'); + $arResult['bitrixPaymentList'][1]['ID'] = 'N'; //saved cat params - $optionsOrderTypes = unserialize(COption::GetOptionString($mid, 'order_types_arr', 0)); - $optionsDelivTypes = unserialize(COption::GetOptionString($mid, 'deliv_types_arr', 0)); - $optionsPayTypes = unserialize(COption::GetOptionString($mid, 'pay_types_arr', 0)); - $optionsPayStatuses = unserialize(COption::GetOptionString($mid, 'pay_statuses_arr', 0)); + $optionsOrderTypes = unserialize(COption::GetOptionString($mid, $CRM_ORDER_TYPES_ARR, 0)); + $optionsDelivTypes = unserialize(COption::GetOptionString($mid, $CRM_DELIVERY_TYPES_ARR, 0)); + $optionsPayTypes = unserialize(COption::GetOptionString($mid, $CRM_PAYMENT_TYPES, 0)); + $optionsPayStatuses = unserialize(COption::GetOptionString($mid, $CRM_PAYMENT_STATUSES, 0)); // --statuses + $optionsPayment = unserialize(COption::GetOptionString($mid, $CRM_PAYMENT, 0)); $aTabs = array( array( @@ -293,31 +315,51 @@ if (isset($_POST['Update']) && $_POST['Update']=='Y') { - - - - - + + + + + - + + + + + + + + + + + + + + - - - - - - + + + + + + @@ -331,8 +373,8 @@ if (isset($_POST['Update']) && $_POST['Update']=='Y') { - - + + BeginNextTab(); ?> Buttons(); ?> From 139d47d2fc7657a2689bc7fcff3da7c13eaaf7da Mon Sep 17 00:00:00 2001 From: Grisha Pomadchin Date: Mon, 8 Jul 2013 15:11:43 +0400 Subject: [PATCH 2/4] deleted old files --- intaro.crm/classes/general/ICrmApi.php | 435 ------------------------- 1 file changed, 435 deletions(-) delete mode 100644 intaro.crm/classes/general/ICrmApi.php diff --git a/intaro.crm/classes/general/ICrmApi.php b/intaro.crm/classes/general/ICrmApi.php deleted file mode 100644 index c6d67794..00000000 --- a/intaro.crm/classes/general/ICrmApi.php +++ /dev/null @@ -1,435 +0,0 @@ -apiUrl = $crmUrl.'/api/v'.$this->apiVersion.'/'; - $this->apiKey = $apiKey; - } - - - public function getStatusCode() - { - return $this->statusCode; - } - - /* Получение кода статуса и сообщения об ошибке */ - public function getLastError() - { - if (!is_null($this->lastError)) - return $this->statusCode . ' ' . $this->lastError; - else - return null; - } - - /* Псообщения об ошибке */ - public function getLastErrorMessage() - { - return $this->lastError; - } - - - /* Методы для работы с заказами */ - /** - * Получение заказа по id - * - * @param string $id - идентификатор заказа - * @return array - информация о заказе - */ - public function orderGet($id) - { - $url = $this->apiUrl.'orders/'.$id; - $result = $this->curlRequest($url); - return $result; - } - - /** - * Создание заказа - * - * @param array $order- информация о заказе - * @return array - */ - public function orderCreate($order) - { - $dataJson = json_encode($order); - $dataJson = str_replace(self::$jsonReplaceSource, self::$jsonReplaceTarget, - $dataJson); - $parameters = array(); - $parameters['order'] = $dataJson; - - $url = $this->apiUrl.'orders/create'; - $result = $this->curlRequest($url, $parameters, 'POST'); - return $result; - } - - /** - * Изменение заказа - * - * @param array $order- информация о заказе - * @return array - */ - public function orderEdit($order) - { - $dataJson = json_encode($order); - $dataJson = str_replace(self::$jsonReplaceSource, self::$jsonReplaceTarget, - $dataJson); - $parameters = array(); - $parameters['order'] = $dataJson; - - $url = $this->apiUrl.'orders/'.$order['id'].'/edit'; - $result = $this->curlRequest($url, $parameters, 'POST'); - return $result; - } - - /** - * Загрузка нескольких заказов - * - * @param array $orders - массив заказов - * @return array - */ - public function orderUpload($orders) - { - $dataJson = json_encode($orders); - $dataJson = str_replace(self::$jsonReplaceSource, self::$jsonReplaceTarget, - $dataJson); - $parameters = array(); - $parameters['orders'] = $dataJson; - - $url = $this->apiUrl.'orders/upload'; - $result = $this->curlRequest($url, $parameters, 'POST'); - return $result; - } - - /** - * Удаление заказа - * - * @param string $id - идентификатор заказа - * @return array - */ - public function orderDelete($id) - { - $url = $this->apiUrl.'orders/'.$id.'/delete'; - $result = $this->curlRequest($url, array(), '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'; - $parameters = array(); - $parameters['startDate'] = $startDate; - $parameters['endDate'] = $endDate; - $parameters['limit'] = $limit; - $parameters['offset'] = $offset; - - $result = $this->curlRequest($url, $parameters); - return $result; - } - - - /* Методы для работы с клиентами */ - /** - * Получение клиента по id - * - * @param string $id - идентификатор - * @return array - информация о клиенте - */ - public function customerGet($id) - { - $url = $this->apiUrl.'customers/'.$id; - $result = $this->curlRequest($url); - return $result; - } - - /** - * Создание клиента - * - * @param array $customer - информация о клиенте - * @return array - */ - public function customerCreate($customer) - { - $dataJson = json_encode($customer); - $dataJson = str_replace(self::$jsonReplaceSource, self::$jsonReplaceTarget, - $dataJson); - $parameters = array(); - $parameters['customer'] = $dataJson; - - $url = $this->apiUrl.'customers/create'; - $result = $this->curlRequest($url, $parameters, 'POST'); - return $result; - } - - /** - * Редактирование клиента - * - * @param array $customer - информация о клиенте - * @return array - */ - public function customerEdit($customer) - { - $dataJson = json_encode($customer); - $dataJson = str_replace(self::$jsonReplaceSource, self::$jsonReplaceTarget, - $dataJson); - $parameters = array(); - $parameters['customer'] = $dataJson; - - $url = $this->apiUrl.'customers/'.$customer['id'].'/edit'; - $result = $this->curlRequest($url, $parameters, 'POST'); - return $result; - } - - /** - * Удаление клиента - * - * @param string $id - идентификатор - * @return array - */ - public function customerDelete($id) - { - $url = $this->apiUrl.'customers/'.$id.'/delete'; - $result = $this->curlRequest($url, array(), 'POST'); - return $result; - } - - /** - * Получение списка заказов клиента - * - * @param string $id - идентификатор клиента - * @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) - { - $url = $this->apiUrl.'customers/'.$id.'/orders'; - $parameters = array(); - $parameters['startDate'] = $startDate; - $parameters['endDate'] = $endDate; - $parameters['limit'] = $limit; - $parameters['offset'] = $offset; - - $result = $this->curlRequest($url, $parameters); - 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); - $dataJson = str_replace(self::$jsonReplaceSource, self::$jsonReplaceTarget, - $dataJson); - $parameters = array(); - $parameters['deliveryType'] = $dataJson; - - $url = $this->apiUrl.'delivery-types/'.$deliveryType['code'].'/edit'; - $result = $this->curlRequest($url, $parameters, '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); - $dataJson = str_replace(self::$jsonReplaceSource, self::$jsonReplaceTarget, - $dataJson); - $parameters = array(); - $parameters['paymentType'] = $dataJson; - - $url = $this->apiUrl.'payment-types/'.$paymentType['code'].'/edit'; - $result = $this->curlRequest($url, $parameters, '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); - $dataJson = str_replace(self::$jsonReplaceSource, self::$jsonReplaceTarget, - $dataJson); - $parameters = array(); - $parameters['paymentStatus'] = $dataJson; - - $url = $this->apiUrl.'payment-statuses/'.$paymentStatus['code'].'/edit'; - $result = $this->curlRequest($url, $parameters, 'POST'); - return $result; - } - - /** - * Получение списка типов заказа - * - * @return array - массив типов заказа - */ - public function orderTypesList() - { - $url = $this->apiUrl.'reference/order-types'; - $result = $this->curlRequest($url); - return $result; - } - - /** - * Редактирование типа заказа - * - * @param array $paymentType - информация о типе заказа - * @return array - */ - public function orderTypesEdit($orderType) - { - $dataJson = json_encode($orderType); - $dataJson = str_replace(self::$jsonReplaceSource, self::$jsonReplaceTarget, - $dataJson); - $parameters = array(); - $parameters['orderType'] = $dataJson; - - $url = $this->apiUrl.'order-types/'.$paymentType['code'].'/edit'; - $result = $this->curlRequest($url, $parameters, 'POST'); - return $result; - } - - protected function curlRequest($url, $parameters = null, $method = 'GET', $format = 'json') - { - $parameters['apiKey'] = $this->apiKey; - - if ($method == 'GET' && !is_null($parameters)) - $url .= '?'.http_build_query($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, 6); // times out after 6s - - if ($method == 'POST') - { - curl_setopt($ch, CURLOPT_POST, true); - curl_setopt($ch, CURLOPT_POSTFIELDS, $parameters); - } - - $response = curl_exec($ch); - $this->statusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE); - - if (curl_errno($ch)) - { - $this->lastError = 'Curl error: ' . curl_error($ch); - return null; - } - curl_close($ch); - - $result = (array)json_decode($response, true); - if ($result['success'] == false) - { - $this->lastError = $result['errorMsg']; - return null; - } - - $this->lastError = null; - unset($result['success']); - if (count($result) == 0) - return true; - return reset($result); - } -} - -?> From fd34304c5f295fabc8b5c57918b1db32a94dbb4c Mon Sep 17 00:00:00 2001 From: Grisha Pomadchin Date: Tue, 9 Jul 2013 19:03:56 +0400 Subject: [PATCH 3/4] +method to upload orders; +api upd; --- .../classes/general/ICrmOrderActions.php | 256 ++++++++++++++++++ intaro.crm/classes/general/RestApi.php | 167 ++++++++---- intaro.crm/include.php | 5 +- intaro.crm/install/index.php | 4 +- intaro.crm/options.php | 9 +- 5 files changed, 376 insertions(+), 65 deletions(-) create mode 100644 intaro.crm/classes/general/ICrmOrderActions.php diff --git a/intaro.crm/classes/general/ICrmOrderActions.php b/intaro.crm/classes/general/ICrmOrderActions.php new file mode 100644 index 00000000..28e3ecbf --- /dev/null +++ b/intaro.crm/classes/general/ICrmOrderActions.php @@ -0,0 +1,256 @@ +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); + } + + /** + * Mass order uploading func + */ + function uploadOrders() { + + //ini_set('display_errors', 1); + //error_reporting(E_ALL); + + COption::SetOptionString(self::$MODULE_ID, self::$CRM_ORDER_LAST_ID, 0); + + if (!CModule::IncludeModule('iblock')) { + //ShowError(GetMessage("SOA_MODULE_NOT_INSTALL")); + return; + } + if (!CModule::IncludeModule("sale")) { + //ShowError(GetMessage("SOA_MODULE_NOT_INSTALL")); + return; + } + + $resOrders = array(); + + $dbOrder = CSaleOrder::GetList(); + + $lastUpOrderId = COption::GetOptionString(self::$MODULE_ID, self::$CRM_ORDER_LAST_ID, 0); + $lastUpOrderIdNew = 0; + + $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)); + + $api = new IntaroCrm\RestApi($api_host, $api_key); + + while ($arOrder = $dbOrder->GetNext()) { + if ($arOrder['ID'] < $lastUpOrderId) //old orders not to upload + break; + + if(!$lastUpOrderIdNew) + $lastUpOrderIdNew = $arOrder['ID']; + + $arFields = CSaleOrder::GetById($arOrder['ID']); + + if (empty($arFields)) { + //handle err + CEventLog::Add(array( + "SEVERITY" => "SECURITY", + "AUDIT_TYPE_ID" => "IntroCrm\uploadOrders", + "MODULE_ID" => self::$MODULE_ID, + "ITEM_ID" => 'empty($arFields)', + "DESCRIPTION" => "Не корректный заказ.", + )); + + return; + } + + $rsUser = CUser::GetByID($arFields['USER_ID']); + $arUser = $rsUser->Fetch(); + + // 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; + + $addressPersonal = array( + 'index' => self::toJSON($arUser['PERSONAL_ZIP']), + 'country' => self::toJSON(GetCountryByID($arUser['PERSONAL_COUNTRY'])), + 'city' => self::toJSON($arUser['PERSONAL_CITY']), + 'street' => self::toJSON($arUser['PERSONAL_STREET']), + 'building' => self::toJSON($arUser['UF_PERSONAL_BUILDING']), + 'flat' => self::toJSON($arUser['UF_PERSONAL_FLAT']), + 'notes' => self::toJSON($arUser['PERSONAL_NOTES']), + 'text' => self::toJSON($arUser['UF_PERSONAL_TEXT']), + 'type' => 'home' + ); + $addresses[] = $addressPersonal; + + $addressWork = array( + 'index' => self::toJSON($arUser['WORK_ZIP']), + 'country' => self::toJSON(GetCountryByID($arUser['WORK_COUNTRY'])), + 'city' => self::toJSON($arUser['WORK_CITY']), + 'street' => self::toJSON($arUser['WORK_STREET']), + 'building' => self::toJSON($arUser['UF_WORK_BUILDING']), // -- + 'flat' => self::toJSON($arUser['UF_WORK_FLAT']), + 'notes' => self::toJSON($arUser['PERSONAL_NOTES']), + 'text' => self::toJSON($arUser['UF_WORK_TEXT']), + 'type' => 'work' + ); + $addresses[] = $addressWork; + + $result = array( + 'externalId' => $arFields['USER_ID'], + 'lastName' => $lastName, + 'firstName' => $firstName, + 'patronymic' => $patronymic, + 'phones' => $phones, + 'addresses' => $addresses + ); + + $customer = $api->customerEdit($result); + + // error pushing customer + if (!$customer) { + // handle + CEventLog::Add(array( + "SEVERITY" => "SECURITY", + "AUDIT_TYPE_ID" => "IntroCrm\uploadOrders", + "MODULE_ID" => self::$MODULE_ID, + "ITEM_ID" => "customerEdit", + "DESCRIPTION" => $api->getLastError(), + )); + + return; + } + + // 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(); + + $rsOrderProps = CSaleOrderPropsValue::GetList(array(), array('ORDER_ID' => $arFields['ID'])); + while ($ar = $rsOrderProps->Fetch()) { + switch ($ar['CODE']) { + case 'ZIP': $resOrderDeliveryAddress['index'] = self::toJSON($ar['VALUE']); + break; + case 'CITY': $resOrderDeliveryAddress['city'] = self::toJSON($ar['VALUE']); + break; + case 'ADDRESS': $resOrderDeliveryAddress['text'] = self::toJSON($ar['VALUE']); + break; + case 'FIO': $resOrder['contactName'] = self::toJSON($ar['VALUE']); + break; + case 'PHONE': $resOrder['phone'] = $ar['VALUE']; + break; + case 'EMAIL': $resOrder['email'] = $ar['VALUE']; + break; + } + } + + $resOrder['deliveryCost'] = $arFields['PRICE_DELIVERY']; + $resOrder['summ'] = $arFields['PRICE']; + $resOrder['markDateTime'] = $arFields['DATE_MARKED']; + $resOrder['externalId'] = $arFields['ID']; + $resOrder['customerId'] = $arFields['USER_ID']; + + $resOrder['paymentType'] = $optionsPayTypes[$arFields['PAY_SYSTEM_ID']]; + $resOrder['paymentStatus'] = $optionsPayment[$arFields['PAYED']]; + $resOrder['orderType'] = $optionsOrderTypes[$arFields['PERSON_TYPE_ID']]; + $resOrder['deliveryType'] = $optionsDelivTypes[$resultDeliveryTypeId]; + $resOrder['status'] = $optionsPayStatuses[$arFields['STATUS_ID']]; + + $resOrder['deliveryAddress'] = $resOrderDeliveryAddress; + + $items = array(); + + $rsOrderBasket = CSaleBasket::GetList(array('PRODUCT_ID' => 'ASC'), array('ORDER_ID' => $arFields['ID'])); + while ($p = $rsOrderBasket->Fetch()) { + $items[] = array( + 'price' => $p['PRICE'], + 'discount' => $p['DISCOUNT_VALUE'], + 'quantity' => $p['QUANTITY'], + 'productId' => $p['PRODUCT_ID'], + 'productName' => self::toJSON($p['NAME']) + ); + } + + $resOrder['items'] = $items; + $resOrders[] = $resOrder; + } + + $orders = $api->orderUpload($resOrders); + + // error pushing orders + if(!$orders) { + //handle err + CEventLog::Add(array( + "SEVERITY" => "SECURITY", + "AUDIT_TYPE_ID" => "IntroCrm\uploadOrders", + "MODULE_ID" => self::$MODULE_ID, + "ITEM_ID" => "orderUpload", + "DESCRIPTION" => $api->getLastError(), + )); + + return; + } + + COption::SetOptionString(self::$MODULE_ID, self::$CRM_ORDER_LAST_ID, $lastUpOrderIdNew); + + return; //all ok! + } +} + +?> diff --git a/intaro.crm/classes/general/RestApi.php b/intaro.crm/classes/general/RestApi.php index cef13009..9900cebe 100644 --- a/intaro.crm/classes/general/RestApi.php +++ b/intaro.crm/classes/general/RestApi.php @@ -33,6 +33,7 @@ class RestApi protected $apiVersion = '1'; protected $lastError; protected $statusCode; + protected $parameters; /** * @param string $crmUrl - адрес CRM @@ -42,6 +43,7 @@ class RestApi { $this->apiUrl = $crmUrl.'/api/v'.$this->apiVersion.'/'; $this->apiKey = $apiKey; + $this->parameters = array('apiKey' => $this->apiKey); } @@ -71,11 +73,15 @@ class RestApi * Получение заказа по id * * @param string $id - идентификатор заказа + * @param string $by - поиск заказа по id или externalId * @return array - информация о заказе */ - public function orderGet($id) + public function orderGet($id, $by = 'externalId') { $url = $this->apiUrl.'orders/'.$id; + + if ($by != 'externalId') + $this->parameters['by'] = $by; $result = $this->curlRequest($url); return $result; } @@ -91,11 +97,10 @@ class RestApi $dataJson = json_encode($order); $dataJson = str_replace(self::$jsonReplaceSource, self::$jsonReplaceTarget, $dataJson); - $parameters = array(); - $parameters['order'] = $dataJson; + $this->parameters['order'] = $dataJson; $url = $this->apiUrl.'orders/create'; - $result = $this->curlRequest($url, $parameters, 'POST'); + $result = $this->curlRequest($url, 'POST'); return $result; } @@ -110,11 +115,10 @@ class RestApi $dataJson = json_encode($order); $dataJson = str_replace(self::$jsonReplaceSource, self::$jsonReplaceTarget, $dataJson); - $parameters = array(); - $parameters['order'] = $dataJson; + $this->parameters['order'] = $dataJson; - $url = $this->apiUrl.'orders/'.$order['id'].'/edit'; - $result = $this->curlRequest($url, $parameters, 'POST'); + $url = $this->apiUrl.'orders/'.$order['externalId'].'/edit'; + $result = $this->curlRequest($url, 'POST'); return $result; } @@ -129,11 +133,10 @@ class RestApi $dataJson = json_encode($orders); $dataJson = str_replace(self::$jsonReplaceSource, self::$jsonReplaceTarget, $dataJson); - $parameters = array(); - $parameters['orders'] = $dataJson; + $this->parameters['orders'] = $dataJson; $url = $this->apiUrl.'orders/upload'; - $result = $this->curlRequest($url, $parameters, 'POST'); + $result = $this->curlRequest($url, 'POST'); return $result; } @@ -141,12 +144,15 @@ class RestApi * Удаление заказа * * @param string $id - идентификатор заказа + * @param string $by - поиск заказа по id или externalId * @return array */ - public function orderDelete($id) + public function orderDelete($id, $by = 'externalId') { $url = $this->apiUrl.'orders/'.$id.'/delete'; - $result = $this->curlRequest($url, array(), 'POST'); + if ($by != 'externalId') + $this->parameters['by'] = $by; + $result = $this->curlRequest($url, 'POST'); return $result; } @@ -162,13 +168,12 @@ class RestApi public function orderHistory($startDate = null, $endDate = null, $limit = 100, $offset = 0) { $url = $this->apiUrl.'orders/history'; - $parameters = array(); - $parameters['startDate'] = $startDate; - $parameters['endDate'] = $endDate; - $parameters['limit'] = $limit; - $parameters['offset'] = $offset; + $this->parameters['startDate'] = $startDate; + $this->parameters['endDate'] = $endDate; + $this->parameters['limit'] = $limit; + $this->parameters['offset'] = $offset; - $result = $this->curlRequest($url, $parameters); + $result = $this->curlRequest($url); return $result; } @@ -178,11 +183,14 @@ class RestApi * Получение клиента по id * * @param string $id - идентификатор + * @param string $by - поиск заказа по id или externalId * @return array - информация о клиенте */ - public function customerGet($id) + public function customerGet($id, $by = 'externalId') { $url = $this->apiUrl.'customers/'.$id; + if ($by != 'externalId') + $this->parameters['by'] = $by; $result = $this->curlRequest($url); return $result; } @@ -198,11 +206,10 @@ class RestApi $dataJson = json_encode($customer); $dataJson = str_replace(self::$jsonReplaceSource, self::$jsonReplaceTarget, $dataJson); - $parameters = array(); - $parameters['customer'] = $dataJson; + $this->parameters['customer'] = $dataJson; $url = $this->apiUrl.'customers/create'; - $result = $this->curlRequest($url, $parameters, 'POST'); + $result = $this->curlRequest($url, 'POST'); return $result; } @@ -217,11 +224,10 @@ class RestApi $dataJson = json_encode($customer); $dataJson = str_replace(self::$jsonReplaceSource, self::$jsonReplaceTarget, $dataJson); - $parameters = array(); - $parameters['customer'] = $dataJson; + $this->parameters['customer'] = $dataJson; - $url = $this->apiUrl.'customers/'.$customer['id'].'/edit'; - $result = $this->curlRequest($url, $parameters, 'POST'); + $url = $this->apiUrl.'customers/'.$customer['externalId'].'/edit'; + $result = $this->curlRequest($url, 'POST'); return $result; } @@ -229,12 +235,15 @@ class RestApi * Удаление клиента * * @param string $id - идентификатор + * @param string $by - поиск заказа по id или externalId * @return array */ - public function customerDelete($id) + public function customerDelete($id, $by = 'externalId') { $url = $this->apiUrl.'customers/'.$id.'/delete'; - $result = $this->curlRequest($url, array(), 'POST'); + if ($by != 'externalId') + $this->parameters['by'] = $by; + $result = $this->curlRequest($url, 'POST'); return $result; } @@ -242,6 +251,7 @@ class RestApi * Получение списка заказов клиента * * @param string $id - идентификатор клиента + * @param string $by - поиск заказа по id или externalId * @param DateTime $startDate - начальная дата выборки * @param DateTime $endDate - конечная дата * @param int $limit - ограничение на размер выборки @@ -249,16 +259,17 @@ class RestApi * @return array - массив заказов */ public function customerOrdersList($id, $startDate = null, $endDate = null, - $limit = 100, $offset = 0) + $limit = 100, $offset = 0, $by = 'externalId') { $url = $this->apiUrl.'customers/'.$id.'/orders'; - $parameters = array(); - $parameters['startDate'] = $startDate; - $parameters['endDate'] = $endDate; - $parameters['limit'] = $limit; - $parameters['offset'] = $offset; + 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, $parameters); + $result = $this->curlRequest($url); return $result; } @@ -286,11 +297,10 @@ class RestApi $dataJson = json_encode($deliveryType); $dataJson = str_replace(self::$jsonReplaceSource, self::$jsonReplaceTarget, $dataJson); - $parameters = array(); - $parameters['deliveryType'] = $dataJson; + $this->parameters['deliveryType'] = $dataJson; $url = $this->apiUrl.'delivery-types/'.$deliveryType['code'].'/edit'; - $result = $this->curlRequest($url, $parameters, 'POST'); + $result = $this->curlRequest($url, 'POST'); return $result; } @@ -318,11 +328,10 @@ class RestApi $dataJson = json_encode($paymentType); $dataJson = str_replace(self::$jsonReplaceSource, self::$jsonReplaceTarget, $dataJson); - $parameters = array(); - $parameters['paymentType'] = $dataJson; + $this->parameters['paymentType'] = $dataJson; $url = $this->apiUrl.'payment-types/'.$paymentType['code'].'/edit'; - $result = $this->curlRequest($url, $parameters, 'POST'); + $result = $this->curlRequest($url, 'POST'); return $result; } @@ -350,11 +359,10 @@ class RestApi $dataJson = json_encode($paymentStatus); $dataJson = str_replace(self::$jsonReplaceSource, self::$jsonReplaceTarget, $dataJson); - $parameters = array(); - $parameters['paymentStatus'] = $dataJson; + $this->parameters['paymentStatus'] = $dataJson; $url = $this->apiUrl.'payment-statuses/'.$paymentStatus['code'].'/edit'; - $result = $this->curlRequest($url, $parameters, 'POST'); + $result = $this->curlRequest($url, 'POST'); return $result; } @@ -374,7 +382,7 @@ class RestApi /** * Редактирование типа заказа * - * @param array $paymentType - информация о типе заказа + * @param array $orderType - информация о типе заказа * @return array */ public function orderTypesEdit($orderType) @@ -382,39 +390,82 @@ class RestApi $dataJson = json_encode($orderType); $dataJson = str_replace(self::$jsonReplaceSource, self::$jsonReplaceTarget, $dataJson); - $parameters = array(); - $parameters['orderType'] = $dataJson; + $this->parameters['orderType'] = $dataJson; - $url = $this->apiUrl.'order-types/'.$paymentType['code'].'/edit'; - $result = $this->curlRequest($url, $parameters, 'POST'); + $url = $this->apiUrl.'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); + $dataJson = str_replace(self::$jsonReplaceSource, self::$jsonReplaceTarget, + $dataJson); + $this->parameters['status'] = $dataJson; + + $url = $this->apiUrl.'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; } - protected function curlRequest($url, $parameters = null, $method = 'GET', $format = 'json') + protected function curlRequest($url, $method = 'GET', $format = 'json') { - $parameters['apiKey'] = $this->apiKey; - - if ($method == 'GET' && !is_null($parameters)) - $url .= '?'.http_build_query($parameters); + 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, 3); // times out after 3s + curl_setopt($ch, CURLOPT_TIMEOUT, 30); // times out after 30s if ($method == 'POST') { curl_setopt($ch, CURLOPT_POST, true); - curl_setopt($ch, CURLOPT_POSTFIELDS, $parameters); + 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)) { @@ -438,4 +489,4 @@ class RestApi } } -?> +?> \ No newline at end of file diff --git a/intaro.crm/include.php b/intaro.crm/include.php index 8acabe55..bedaf9b5 100644 --- a/intaro.crm/include.php +++ b/intaro.crm/include.php @@ -1,8 +1,9 @@ 'classes/general/RestApi.php' + 'IntaroCrm\RestApi' => 'classes/general/RestApi.php', + 'ICrmOrderActions' => 'classes/general/ICrmOrderActions.php' ) ); ?> diff --git a/intaro.crm/install/index.php b/intaro.crm/install/index.php index 767dff67..c7e89eb5 100644 --- a/intaro.crm/install/index.php +++ b/intaro.crm/install/index.php @@ -29,6 +29,7 @@ class intaro_crm extends CModule var $CRM_PAYMENT_TYPES = 'pay_types_arr'; var $CRM_PAYMENT_STATUSES = 'pay_statuses_arr'; var $CRM_PAYMENT = 'payment_arr'; //order payment Y/N + var $CRM_ORDER_LAST_ID = 'order_last_id'; var $INSTALL_PATH; @@ -107,7 +108,7 @@ class intaro_crm extends CModule $arResult['deliveryTypesList'] = $this->INTARO_CRM_API->deliveryTypesList(); $arResult['paymentTypesList'] = $this->INTARO_CRM_API->paymentTypesList(); $arResult['paymentStatusesList'] = $this->INTARO_CRM_API->paymentStatusesList(); // --statuses - //$arResult['payment'] = $this->INTARO_CRM_API->getPymentsList() -- not exist + $arResult['paymentList'] = $this->INTARO_CRM_API->orderStatusesList(); //bitrix orderTypesList -- personTypes $dbOrderTypesList = CSalePersonType::GetList( @@ -307,6 +308,7 @@ class intaro_crm extends CModule COption::RemoveOption($this->MODULE_ID, $this->CRM_PAYMENT_TYPES); COption::RemoveOption($this->MODULE_ID, $this->CRM_PAYMENT_STATUSES); COption::RemoveOption($this->MODULE_ID, $this->CRM_PAYMENT); + COption::RemoveOption($this->MODULE_ID, $this->CRM_ORDER_LAST_ID); $APPLICATION->IncludeAdminFile( GetMessage('MODULE_UNINSTALL_TITLE'), diff --git a/intaro.crm/options.php b/intaro.crm/options.php index 7ec8d250..9325bbe3 100644 --- a/intaro.crm/options.php +++ b/intaro.crm/options.php @@ -10,6 +10,7 @@ $CRM_DELIVERY_TYPES_ARR = 'deliv_types_arr'; $CRM_PAYMENT_TYPES = 'pay_types_arr'; $CRM_PAYMENT_STATUSES = 'pay_statuses_arr'; $CRM_PAYMENT = 'payment_arr'; //order payment Y/N +$CRM_ORDER_LAST_ID = 'order_last_id'; CModule::IncludeModule('intaro.crm'); CModule::IncludeModule('sale'); @@ -139,8 +140,8 @@ if (isset($_POST['Update']) && $_POST['Update']=='Y') { $uri .= '&ok=Y'; LocalRedirect($uri); } else { - $api_host = COption::GetOptionString($mid, 'api_host', 0); - $api_key = COption::GetOptionString($mid, 'api_key', 0); + $api_host = COption::GetOptionString($mid, $CRM_API_HOST_OPTION, 0); + $api_key = COption::GetOptionString($mid, $CRM_API_KEY_OPTION, 0); $api = new IntaroCrm\RestApi($api_host, $api_key); @@ -149,7 +150,7 @@ if (isset($_POST['Update']) && $_POST['Update']=='Y') { $arResult['deliveryTypesList'] = $api->deliveryTypesList(); $arResult['paymentTypesList'] = $api->paymentTypesList(); $arResult['paymentStatusesList'] = $api->paymentStatusesList(); // --statuses - //$arResult['payment'] = $this->INTARO_CRM_API->getPymentsList() -- not exist + $arResult['paymentList'] = $api->orderStatusesList(); //bitrix orderTypesList -- personTypes $dbOrderTypesList = CSalePersonType::GetList( @@ -250,7 +251,7 @@ if (isset($_POST['Update']) && $_POST['Update']=='Y') { "DIV" => "edit2", "TAB" => GetMessage('ICRM_OPTIONS_CATALOG_TAB'), "ICON" => '', - "TITLE" => GetMessage('ICRM_OPTIONS_IMPORT_CAPTION') + "TITLE" => GetMessage('ICRM_OPTIONS_CATALOG_CAPTION') ), ); $tabControl = new CAdminTabControl("tabControl", $aTabs); From d5474cf91ba7d1ad757204b412261ba1d0f60f5e Mon Sep 17 00:00:00 2001 From: Grisha Pomadchin Date: Wed, 10 Jul 2013 16:53:49 +0400 Subject: [PATCH 4/4] +agent; todo: orderHistoryUpdate; v0.3a; --- .../classes/general/ICrmOrderActions.php | 148 +++++++++++------- intaro.crm/install/index.php | 20 ++- intaro.crm/install/version.php | 4 +- 3 files changed, 113 insertions(+), 59 deletions(-) diff --git a/intaro.crm/classes/general/ICrmOrderActions.php b/intaro.crm/classes/general/ICrmOrderActions.php index 28e3ecbf..84ad3306 100644 --- a/intaro.crm/classes/general/ICrmOrderActions.php +++ b/intaro.crm/classes/general/ICrmOrderActions.php @@ -3,15 +3,15 @@ class ICrmOrderActions { - public static $MODULE_ID = 'intaro.crm'; - public static $CRM_API_HOST_OPTION = 'api_host'; - public static $CRM_API_KEY_OPTION = 'api_key'; - public static $CRM_ORDER_TYPES_ARR = 'order_types_arr'; - public static $CRM_DELIVERY_TYPES_ARR = 'deliv_types_arr'; - public static $CRM_PAYMENT_TYPES = 'pay_types_arr'; - public static $CRM_PAYMENT_STATUSES = 'pay_statuses_arr'; - public static $CRM_PAYMENT = 'payment_arr'; //order payment Y/N - public static $CRM_ORDER_LAST_ID = 'order_last_id'; + protected static $MODULE_ID = 'intaro.crm'; + protected static $CRM_API_HOST_OPTION = 'api_host'; + protected static $CRM_API_KEY_OPTION = 'api_key'; + protected static $CRM_ORDER_TYPES_ARR = 'order_types_arr'; + protected static $CRM_DELIVERY_TYPES_ARR = 'deliv_types_arr'; + protected static $CRM_PAYMENT_TYPES = 'pay_types_arr'; + protected static $CRM_PAYMENT_STATUSES = 'pay_statuses_arr'; + protected static $CRM_PAYMENT = 'payment_arr'; //order payment Y/N + protected static $CRM_ORDER_LAST_ID = 'order_last_id'; /** * @@ -19,7 +19,7 @@ class ICrmOrderActions * @param type $str in SITE_CHARSET * @return type $str in utf-8 */ - public static function toJSON($str) { + protected static function toJSON($str) { global $APPLICATION; return $APPLICATION->ConvertCharset($str, SITE_CHARSET, 'utf-8'); @@ -40,20 +40,26 @@ class ICrmOrderActions /** * Mass order uploading func */ - function uploadOrders() { + public static function uploadOrders() { - //ini_set('display_errors', 1); - //error_reporting(E_ALL); - - COption::SetOptionString(self::$MODULE_ID, self::$CRM_ORDER_LAST_ID, 0); + //COption::SetOptionString(self::$MODULE_ID, self::$CRM_ORDER_LAST_ID, 0); // -- for test if (!CModule::IncludeModule('iblock')) { - //ShowError(GetMessage("SOA_MODULE_NOT_INSTALL")); - return; + //handle err + self::eventLog('iblock', 'module not found'); + return false; } + if (!CModule::IncludeModule("sale")) { - //ShowError(GetMessage("SOA_MODULE_NOT_INSTALL")); - return; + //handle err + self::eventLog('sale', 'module not found'); + return false; + } + + if (!CModule::IncludeModule("catalog")) { + //handle err + self::eventLog('catalog', 'module not found'); + return false; } $resOrders = array(); @@ -76,8 +82,8 @@ class ICrmOrderActions $api = new IntaroCrm\RestApi($api_host, $api_key); while ($arOrder = $dbOrder->GetNext()) { - if ($arOrder['ID'] < $lastUpOrderId) //old orders not to upload - break; + if ($arOrder['ID'] <= $lastUpOrderId) //old orders not to upload + return true; if(!$lastUpOrderIdNew) $lastUpOrderIdNew = $arOrder['ID']; @@ -86,15 +92,9 @@ class ICrmOrderActions if (empty($arFields)) { //handle err - CEventLog::Add(array( - "SEVERITY" => "SECURITY", - "AUDIT_TYPE_ID" => "IntroCrm\uploadOrders", - "MODULE_ID" => self::$MODULE_ID, - "ITEM_ID" => 'empty($arFields)', - "DESCRIPTION" => "Не корректный заказ.", - )); + self::eventLog('empty($arFields)', 'incorrect order'); - return; + return false; } $rsUser = CUser::GetByID($arFields['USER_ID']); @@ -144,7 +144,7 @@ class ICrmOrderActions $addresses[] = $addressWork; $result = array( - 'externalId' => $arFields['USER_ID'], + 'externalId' => $arFields['USER_ID'], 'lastName' => $lastName, 'firstName' => $firstName, 'patronymic' => $patronymic, @@ -156,16 +156,9 @@ class ICrmOrderActions // error pushing customer if (!$customer) { - // handle - CEventLog::Add(array( - "SEVERITY" => "SECURITY", - "AUDIT_TYPE_ID" => "IntroCrm\uploadOrders", - "MODULE_ID" => self::$MODULE_ID, - "ITEM_ID" => "customerEdit", - "DESCRIPTION" => $api->getLastError(), - )); - - return; + //handle err + self::eventLog('IntaroCrm\RestApi::customerEdit', $api->getLastError()); + return false; } // delivery types @@ -218,12 +211,19 @@ class ICrmOrderActions $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 = ''; + $items[] = array( - 'price' => $p['PRICE'], - 'discount' => $p['DISCOUNT_VALUE'], - 'quantity' => $p['QUANTITY'], - 'productId' => $p['PRODUCT_ID'], - 'productName' => self::toJSON($p['NAME']) + 'price' => $p['PRICE'], + 'purchasePrice' => $pr, + 'discount' => $p['DISCOUNT_VALUE'], + 'quantity' => $p['QUANTITY'], + 'productId' => $p['PRODUCT_ID'], + 'productName' => self::toJSON($p['NAME']) ); } @@ -236,21 +236,57 @@ class ICrmOrderActions // error pushing orders if(!$orders) { //handle err - CEventLog::Add(array( - "SEVERITY" => "SECURITY", - "AUDIT_TYPE_ID" => "IntroCrm\uploadOrders", - "MODULE_ID" => self::$MODULE_ID, - "ITEM_ID" => "orderUpload", - "DESCRIPTION" => $api->getLastError(), - )); - - return; + self::eventLog('IntaroCrm\RestApi::orderUpload', $api->getLastError()); + return false; } COption::SetOptionString(self::$MODULE_ID, self::$CRM_ORDER_LAST_ID, $lastUpOrderIdNew); - return; //all ok! + return true; //all ok! } + + /** + * + * w event in bitrix log + * @param type $auditType + * @param type $itemId + * @param type $description + */ + private static function eventLog($itemId, $description) { + CEventLog::Add(array( + "SEVERITY" => "SECURITY", + "AUDIT_TYPE_ID" => 'ICrmOrderActions::uploadOrders', + "MODULE_ID" => self::$MODULE_ID, + "ITEM_ID" => $itemId, + "DESCRIPTION" => $description, + )); + + self::sendEmail($itemId, $description); + } + + private static function sendEmail($itemId, $description) { + $title = 'Error: Intaro CRM.'; + $text = 'Error: ' . $itemId . ' - ' . $description; + $to = COption::GetOptionString("main", "email_from"); + $from = COption::GetOptionString("main", "email_from"); + mail($to, $title, $text, 'From:'.$from); + } + + /** + * + * Agent function + * + * @return self name + */ + + public static function uploadOrdersAgent() { + + if(self::uploadOrders()) + return 'ICrmOrderActions::uploadOrdersAgent();'; + + else return; + + } + } - ?> diff --git a/intaro.crm/install/index.php b/intaro.crm/install/index.php index c7e89eb5..8ad94915 100644 --- a/intaro.crm/install/index.php +++ b/intaro.crm/install/index.php @@ -288,8 +288,25 @@ class intaro_crm extends CModule COption::SetOptionString($this->MODULE_ID, $this->CRM_PAYMENT_TYPES, serialize($paymentTypesArr)); COption::SetOptionString($this->MODULE_ID, $this->CRM_PAYMENT_STATUSES, serialize($paymentStatusesArr)); COption::SetOptionString($this->MODULE_ID, $this->CRM_PAYMENT, serialize($paymentArr)); + COption::SetOptionString($this->MODULE_ID, $this->CRM_ORDER_LAST_ID, 0); RegisterModule($this->MODULE_ID); + //agent + $dateAgent = new DateTime(); + $intAgent = new DateInterval('PT60S'); + $dateAgent->add($intAgent); + + CAgent::AddAgent( + "ICrmOrderActions::uploadOrdersAgent();", + $this->MODULE_ID, + "N", + 600, // interval - 10 mins + $dateAgent->format('d.m.Y H:i:s'), // date of first check + "Y", // агент активен + $dateAgent->format('d.m.Y H:i:s'), // date of first start + 30 + ); + $APPLICATION->IncludeAdminFile( GetMessage('MODULE_INSTALL_TITLE'), $_SERVER['DOCUMENT_ROOT'] . '/bitrix/modules/' . $this->MODULE_ID . '/install/step3.php' @@ -299,7 +316,8 @@ class intaro_crm extends CModule function DoUninstall() { global $APPLICATION; - + + CAgent::RemoveAgent("ICrmOrderActions::uploadOrdersAgent();", $this->MODULE_ID); UnRegisterModule($this->MODULE_ID); COption::RemoveOption($this->MODULE_ID, $this->CRM_API_HOST_OPTION); diff --git a/intaro.crm/install/version.php b/intaro.crm/install/version.php index 560d26eb..c65aac0c 100644 --- a/intaro.crm/install/version.php +++ b/intaro.crm/install/version.php @@ -1,6 +1,6 @@ '0.2a', - 'VERSION_DATE' => '2013-07-08 15:04:00', + 'VERSION' => '0.3a', + 'VERSION_DATE' => '2013-07-10 16:49:00', ); ?>