diff --git a/intaro.intarocrm/classes/general/ICMLLoader.php b/intaro.intarocrm/classes/general/ICMLLoader.php
index ec3b5827..2b91b439 100644
--- a/intaro.intarocrm/classes/general/ICMLLoader.php
+++ b/intaro.intarocrm/classes/general/ICMLLoader.php
@@ -31,7 +31,7 @@ class ICMLLoader {
$this->PrepareSettings();
- $this->fp = $this->PrepareFile($this->filename);
+ $this->fp = $this->PrepareFile($this->filename. '.tmp');
if ($this->isLogged) {
$this->fpLog = $this->PrepareFile($this->logFile);
@@ -57,6 +57,8 @@ class ICMLLoader {
$this->CloseFile($this->fp);
$this->CloseFile($this->fpLog);
+ unlink($_SERVER["DOCUMENT_ROOT"] . $this->filename);
+ rename($_SERVER["DOCUMENT_ROOT"] . $this->filename. '.tmp', $_SERVER["DOCUMENT_ROOT"] . $this->filename);
return true;
diff --git a/intaro.intarocrm/classes/general/ICrmOrderActions.php b/intaro.intarocrm/classes/general/ICrmOrderActions.php
index 8f498638..c8f39018 100755
--- a/intaro.intarocrm/classes/general/ICrmOrderActions.php
+++ b/intaro.intarocrm/classes/general/ICrmOrderActions.php
@@ -1,966 +1,969 @@
- "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;
- }
-
- $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);
-
- //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);
-
- $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) {
-
- 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(
- 'LID' => $defaultSiteId, //<----!
- 'PERSON_TYPE_ID' => $optionsOrderTypes[$order['orderType']], // <------!
- 'PAYED' => 'N',
- 'CANCELED' => 'N',
- 'STATUS_ID' => 'N',
- 'PRICE' => 0,
- 'CURRENCY' => 'RUB',
- '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($newOrderFields);
-
- $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']) {
- $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) {
- // 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(
- array('PRODUCT_ID' => 'ASC'),
- array('ORDER_ID' => $order['externalId'], 'PRODUCT_ID' => $item['offer']['externalId']))->Fetch();
-
- if(!$p)
- $p = CIBlockElement::GetByID($item['offer']['externalId'])->Fetch();
-
- // change existing basket items
- $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' => $productPrice['CURRENCY'],
- 'LID' => $LID,
- 'PRODUCT_ID' => $item['offer']['externalId'],
- 'PRODUCT_PRICE_ID' => $p['PRODUCT_PRICE_ID'],
- 'WEIGHT' => $p['WEIGHT'],
- 'DELAY' => $p['DELAY'],
- 'CAN_BUY' => $p['CAN_BUY'],
- 'MODULE' => $p['MODULE'],
- 'NOTES' => $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'] = $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['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);
- }
-
- // 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);
-
- $dateStart = new \DateTime();
- }
- }
-
- if(count($orderHistory))
- COption::SetOptionString(self::$MODULE_ID, self::$CRM_ORDER_HISTORY_DATE, $dateStart->format('Y-m-d H:i:s'));
-
- 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'].$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,
- 'discount' => $arFields['DISCOUNT_PRICE'],
- 'discountPercent' => $arFields['DISCOUNT_VALUE'],
- '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'];
- }
+ "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;
+ }
+
+ $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);
+
+ //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);
+
+ $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) {
+
+ 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(
+ 'LID' => $defaultSiteId, //<----!
+ 'PERSON_TYPE_ID' => $optionsOrderTypes[$order['orderType']], // <------!
+ 'PAYED' => 'N',
+ 'CANCELED' => 'N',
+ 'STATUS_ID' => 'N',
+ 'PRICE' => 0,
+ 'CURRENCY' => 'RUB',
+ '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'])
+ $GLOBALS['ICRM_ACCOUNT_NUMBER'] = $order['number'];
+
+ $order['externalId'] = CSaleOrder::Add($newOrderFields);
+
+ if(isset($GLOBALS['ICRM_ACCOUNT_NUMBER']))
+ unset($GLOBALS['ICRM_ACCOUNT_NUMBER']);
+
+ $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']) {
+ $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) {
+ // 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(
+ array('PRODUCT_ID' => 'ASC'),
+ array('ORDER_ID' => $order['externalId'], 'PRODUCT_ID' => $item['offer']['externalId']))->Fetch();
+
+ if(!$p)
+ $p = CIBlockElement::GetByID($item['offer']['externalId'])->Fetch();
+
+ // change existing basket items
+ $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' => $productPrice['CURRENCY'],
+ 'LID' => $LID,
+ 'PRODUCT_ID' => $item['offer']['externalId'],
+ 'PRODUCT_PRICE_ID' => $p['PRODUCT_PRICE_ID'],
+ 'WEIGHT' => $p['WEIGHT'],
+ 'DELAY' => $p['DELAY'],
+ 'CAN_BUY' => $p['CAN_BUY'],
+ 'MODULE' => $p['MODULE'],
+ 'NOTES' => $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'] = $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['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);
+ }
+
+ // 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);
+
+ $dateStart = new \DateTime();
+ }
+ }
+
+ if(count($orderHistory))
+ COption::SetOptionString(self::$MODULE_ID, self::$CRM_ORDER_HISTORY_DATE, $dateStart->format('Y-m-d H:i:s'));
+
+ 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'].$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,
+ 'discount' => $arFields['DISCOUNT_PRICE'],
+ 'discountPercent' => $arFields['DISCOUNT_VALUE'],
+ '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/events/ICrmOrderEvent.php b/intaro.intarocrm/classes/general/events/ICrmOrderEvent.php
index 083ce94f..a35f01a6 100644
--- a/intaro.intarocrm/classes/general/events/ICrmOrderEvent.php
+++ b/intaro.intarocrm/classes/general/events/ICrmOrderEvent.php
@@ -249,4 +249,15 @@ class ICrmOrderEvent {
return true;
}
+
+ /**
+ *
+ * @param type $ID -- orderId
+ * @param type $value -- ACCOUNT_NUMBER
+ * @return boolean
+ */
+ function onBeforeOrderAccountNumberSet($ID, $value) {
+ if(isset($GLOBALS['ICRM_ACCOUNT_NUMBER']) && $GLOBALS['ICRM_ACCOUNT_NUMBER'])
+ return $GLOBALS['ICRM_ACCOUNT_NUMBER'];
+ }
}
\ No newline at end of file
diff --git a/intaro.intarocrm/install/index.php b/intaro.intarocrm/install/index.php
index 373dc2e5..506846d6 100755
--- a/intaro.intarocrm/install/index.php
+++ b/intaro.intarocrm/install/index.php
@@ -1,1119 +1,1121 @@
-INSTALL_PATH = $path;
- include($path . "/version.php");
- $this->MODULE_VERSION = $arModuleVersion["VERSION"];
- $this->MODULE_VERSION_DATE = $arModuleVersion["VERSION_DATE"];
- $this->MODULE_NAME = GetMessage('MODULE_NAME');
- $this->MODULE_DESCRIPTION = GetMessage('MODULE_DESCRIPTION');
- $this->PARTNER_NAME = GetMessage('MODULE_PARTNER_NAME');
- $this->PARTNER_URI = GetMessage('MODULE_PARTNER_URI');
- }
-
- /**
- * Functions DoInstall and DoUninstall are
- * All other functions are optional
- */
- function DoInstall() {
- global $APPLICATION, $step, $arResult;
-
- if (!in_array('curl', get_loaded_extensions())) {
- $APPLICATION->ThrowException(GetMessage("INTAROCRM_CURL_ERR"));
- return false;
- }
-
- if (!date_default_timezone_get()) {
- if (!ini_get('date.timezone')) {
- $APPLICATION->ThrowException(GetMessage("DATE_TIMEZONE_ERR"));
- return false;
- }
- }
-
- include($this->INSTALL_PATH . '/../classes/general/RestApi.php');
- include($this->INSTALL_PATH . '/../classes/general/ICrmOrderActions.php');
- include($this->INSTALL_PATH . '/../classes/general/ICMLLoader.php');
-
- $step = intval($_REQUEST['step']);
-
- $arResult['orderProps'] = array(
- array(
- 'NAME' => GetMessage('FIO'),
- 'ID' => 'fio'
- ),
- array(
- 'NAME' => GetMessage('PHONE'),
- 'ID' => 'phone'
- ),
- array(
- 'NAME' => GetMessage('EMAIL'),
- 'ID' => 'email'
- ),
- array(
- 'NAME' => GetMessage('ADDRESS'),
- 'ID' => 'text'
- ),
- // address
- /* array(
- 'NAME' => GetMessage('COUNTRY'),
- 'ID' => 'country'
- ),
- array(
- 'NAME' => GetMessage('REGION'),
- 'ID' => 'region'
- ),
- array(
- 'NAME' => GetMessage('CITY'),
- 'ID' => 'city'
- ), */
- array(
- 'NAME' => GetMessage('ZIP'),
- 'ID' => 'index'
- ),
- array(
- 'NAME' => GetMessage('STREET'),
- 'ID' => 'street'
- ),
- array(
- 'NAME' => GetMessage('BUILDING'),
- 'ID' => 'building'
- ),
- array(
- 'NAME' => GetMessage('FLAT'),
- 'ID' => 'flat'
- ),
- array(
- 'NAME' => GetMessage('INTERCOMCODE'),
- 'ID' => 'intercomcode'
- ),
- array(
- 'NAME' => GetMessage('FLOOR'),
- 'ID' => 'floor'
- ),
- array(
- 'NAME' => GetMessage('BLOCK'),
- 'ID' => 'block'
- ),
- array(
- 'NAME' => GetMessage('HOUSE'),
- 'ID' => 'house'
- )
- );
-
- if ($step <= 1) {
- if (!CModule::IncludeModule("sale")) {
- $arResult['errCode'] = 'ERR_SALE';
- }
-
- if (!CModule::IncludeModule("iblock")) {
- $arResult['errCode'] = 'ERR_IBLOCK';
- }
-
- if (!CModule::IncludeModule("catalog")) {
- $arResult['errCode'] = 'ERR_CATALOG';
- }
-
- $arResult['arSites'] = array();
- $rsSites = CSite::GetList($by, $sort, array());
- while ($ar = $rsSites->Fetch())
- $arResult['arSites'][] = $ar;
-
- $APPLICATION->IncludeAdminFile(
- GetMessage('MODULE_INSTALL_TITLE'), $_SERVER['DOCUMENT_ROOT'] . '/bitrix/modules/' . $this->MODULE_ID . '/install/step1.php'
- );
- } else if ($step == 2) {
-
- if (!CModule::IncludeModule("sale")) {
- $arResult['errCode'] = 'ERR_SALE';
- }
-
- if (!CModule::IncludeModule("iblock")) {
- $arResult['errCode'] = 'ERR_IBLOCK';
- }
-
- if (!CModule::IncludeModule("catalog")) {
- $arResult['errCode'] = 'ERR_CATALOG';
- }
-
- $arResult['arSites'] = array();
- $rsSites = CSite::GetList($by, $sort, array());
- while ($ar = $rsSites->Fetch())
- $arResult['arSites'][] = $ar;
-
- if (isset($arResult['errCode']) && $arResult['errCode']) {
- $APPLICATION->IncludeAdminFile(
- GetMessage('MODULE_INSTALL_TITLE'),
- $_SERVER['DOCUMENT_ROOT'] . '/bitrix/modules/' . $this->MODULE_ID . '/install/step1.php'
- );
- return;
- }
-
- if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && (strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') && isset($_POST['ajax']) && ($_POST['ajax'] == 1)) {
-
- $api_host = COption::GetOptionString($this->MODULE_ID, $this->CRM_API_HOST_OPTION, 0);
- $api_key = COption::GetOptionString($this->MODULE_ID, $this->CRM_API_KEY_OPTION, 0);
- $this->INTARO_CRM_API = new \IntaroCrm\RestApi($api_host, $api_key);
-
- //prepare crm lists
- $arResult['orderTypesList'] = $this->INTARO_CRM_API->orderTypesList();
-
- if ((int) $this->INTARO_CRM_API->getStatusCode() != 200) {
- $APPLICATION->RestartBuffer();
- header('Content-Type: application/x-javascript; charset=' . LANG_CHARSET);
- die(json_encode(array("success" => false)));
- }
-
- $arResult['deliveryTypesList'] = $this->INTARO_CRM_API->deliveryTypesList();
- $arResult['paymentTypesList'] = $this->INTARO_CRM_API->paymentTypesList();
- $arResult['paymentStatusesList'] = $this->INTARO_CRM_API->paymentStatusesList(); // --statuses
- $arResult['paymentList'] = $this->INTARO_CRM_API->orderStatusesList();
- $arResult['paymentGroupList'] = $this->INTARO_CRM_API->orderStatusGroupsList(); // -- statuses groups
- //bitrix orderTypesList -- personTypes
- $dbOrderTypesList = CSalePersonType::GetList(
- array(
- "SORT" => "ASC",
- "NAME" => "ASC"
- ), array(
- "ACTIVE" => "Y",
- ), false, false, array()
- );
-
-
- //form order types ids arr
- $orderTypesArr = array();
- if ($arOrderTypesList = $dbOrderTypesList->Fetch()) {
- do {
- $arResult['bitrixOrderTypesList'][] = $arOrderTypesList;
- $orderTypesArr[$arOrderTypesList['ID']] = htmlspecialchars(trim($_POST['order-type-' . $arOrderTypesList['ID']]));
- } while ($arOrderTypesList = $dbOrderTypesList->Fetch());
- }
-
- //bitrix deliveryTypesList
- $dbDeliveryTypesList = CSaleDelivery::GetList(
- array(
- "SORT" => "ASC",
- "NAME" => "ASC"
- ), array(
- "ACTIVE" => "Y",
- ), false, false, array()
- );
-
- //form delivery types ids arr
- $deliveryTypesArr = array();
- if ($arDeliveryTypesList = $dbDeliveryTypesList->Fetch()) {
- do {
- $arResult['bitrixDeliveryTypesList'][] = $arDeliveryTypesList;
- $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"
- )
- );
-
- //form payment types ids arr
- $paymentTypesArr = array();
- if ($arPaymentTypesList = $dbPaymentTypesList->Fetch()) {
- do {
- $arResult['bitrixPaymentTypesList'][] = $arPaymentTypesList;
- $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"
- )
- );
-
- //form payment statuses ids arr
- $paymentStatusesArr['YY'] = htmlspecialchars(trim($_POST['payment-status-YY']));
- if ($arPaymentStatusesList = $dbPaymentStatusesList->Fetch()) {
- do {
- $arResult['bitrixPaymentStatusesList'][] = $arPaymentStatusesList;
- $paymentStatusesArr[$arPaymentStatusesList['ID']] = htmlspecialchars(trim($_POST['payment-status-' . $arPaymentStatusesList['ID']]));
- } while ($arPaymentStatusesList = $dbPaymentStatusesList->Fetch());
- }
-
- $arResult['bitrixPaymentStatusesList'][] = array(
- 'ID' => 'YY',
- 'NAME' => GetMessage('CANCELED')
- );
-
- //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_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));
-
- // generate updated select inputs
- $input = array();
-
- foreach ($arResult['bitrixDeliveryTypesList'] as $bitrixDeliveryType) {
- $input['delivery-type-' . $bitrixDeliveryType['ID']] =
- '';
- }
-
- foreach ($arResult['bitrixPaymentTypesList'] as $bitrixPaymentType) {
- $input['payment-type-' . $bitrixPaymentType['ID']] =
- '';
- }
-
- foreach ($arResult['bitrixPaymentStatusesList'] as $bitrixPaymentStatus) {
- $input['payment-status-' . $bitrixPaymentStatus['ID']] =
- '';
- }
-
- foreach ($arResult['bitrixPaymentList'] as $bitrixPayment) {
- $input['payment-' . $bitrixPayment['ID']] =
- '';
- }
-
- foreach ($arResult['bitrixOrderTypesList'] as $bitrixOrderType) {
- $input['order-type-' . $bitrixOrderType['ID']] =
- '';
- }
-
- $APPLICATION->RestartBuffer();
- header('Content-Type: application/x-javascript; charset=' . LANG_CHARSET);
- die(json_encode(array("success" => true, "result" => $input)));
- }
-
- $api_host = htmlspecialchars(trim($_POST[$this->CRM_API_HOST_OPTION]));
- $api_key = htmlspecialchars(trim($_POST[$this->CRM_API_KEY_OPTION]));
-
- // empty == select all
- $orderSites = array();
- foreach ($_POST[$this->CRM_ORDER_SITES] as $site) {
- $orderSites[] = htmlspecialchars(trim($site));
- }
-
- // 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) {
- $arResult['errCode'] = 'ERR_FIELDS_API_HOST';
- $APPLICATION->IncludeAdminFile(
- GetMessage('MODULE_INSTALL_TITLE'),
- $_SERVER['DOCUMENT_ROOT'] . '/bitrix/modules/' . $this->MODULE_ID . '/install/step1.php'
- );
- return;
- }
-
- $this->INTARO_CRM_API = new \IntaroCrm\RestApi($api_host, $api_key);
-
- $this->INTARO_CRM_API->paymentStatusesList();
-
- //check connection & apiKey valid
- if ((int) $this->INTARO_CRM_API->getStatusCode() != 200) {
- $arResult['errCode'] = 'ERR_' . $this->INTARO_CRM_API->getStatusCode();
-
- $APPLICATION->IncludeAdminFile(
- GetMessage('MODULE_INSTALL_TITLE'),
- $_SERVER['DOCUMENT_ROOT'] . '/bitrix/modules/' . $this->MODULE_ID . '/install/step1.php'
- );
-
- return;
- }
-
- COption::SetOptionString($this->MODULE_ID, $this->CRM_API_HOST_OPTION, $api_host);
- COption::SetOptionString($this->MODULE_ID, $this->CRM_API_KEY_OPTION, $api_key);
- COption::SetOptionString($this->MODULE_ID, $this->CRM_ORDER_SITES, serialize($orderSites));
-
- //prepare crm lists
- $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(); // --statuses
- $arResult['paymentList'] = $this->INTARO_CRM_API->orderStatusesList();
- $arResult['paymentGroupList'] = $this->INTARO_CRM_API->orderStatusGroupsList(); // -- statuses groups
- //bitrix orderTypesList -- personTypes
- $dbOrderTypesList = CSalePersonType::GetList(
- array(
- "SORT" => "ASC",
- "NAME" => "ASC"
- ), array(
- "ACTIVE" => "Y",
- ), false, false, array()
- );
-
- if ($arOrderTypesList = $dbOrderTypesList->Fetch()) {
- do {
- $arResult['bitrixOrderTypesList'][] = $arOrderTypesList;
- } while ($arOrderTypesList = $dbOrderTypesList->Fetch());
- }
-
- //bitrix deliveryTypesList
- $dbDeliveryTypesList = CSaleDelivery::GetList(
- array(
- "SORT" => "ASC",
- "NAME" => "ASC"
- ), array(
- "ACTIVE" => "Y",
- ), false, false, array()
- );
-
- if ($arDeliveryTypesList = $dbDeliveryTypesList->Fetch()) {
- do {
- $arResult['bitrixDeliveryTypesList'][] = $arDeliveryTypesList;
- } while ($arDeliveryTypesList = $dbDeliveryTypesList->Fetch());
- }
-
- //bitrix paymentTypesList
- $dbPaymentTypesList = CSalePaySystem::GetList(
- array(
- "SORT" => "ASC",
- "NAME" => "ASC"
- ), array(
- "ACTIVE" => "Y"
- )
- );
-
- if ($arPaymentTypesList = $dbPaymentTypesList->Fetch()) {
- do {
- $arResult['bitrixPaymentTypesList'][] = $arPaymentTypesList;
- } while ($arPaymentTypesList = $dbPaymentTypesList->Fetch());
- }
-
- //bitrix paymentStatusesList --statuses
- $dbPaymentStatusesList = CSaleStatus::GetList(
- array(
- "SORT" => "ASC",
- "NAME" => "ASC"
- ), array(
- "LID" => "ru", //ru
- "ACTIVE" => "Y"
- )
- );
-
- if ($arPaymentStatusesList = $dbPaymentStatusesList->Fetch()) {
- do {
- $arResult['bitrixPaymentStatusesList'][] = $arPaymentStatusesList;
- } while ($arPaymentStatusesList = $dbPaymentStatusesList->Fetch());
- }
-
- $arResult['bitrixPaymentStatusesList'][] = array(
- 'ID' => 'YY',
- 'NAME' => GetMessage('CANCELED')
- );
-
- $APPLICATION->IncludeAdminFile(
- GetMessage('MODULE_INSTALL_TITLE'),
- $_SERVER['DOCUMENT_ROOT'] . '/bitrix/modules/' . $this->MODULE_ID . '/install/step2.php'
- );
- } else if ($step == 3) {
- if (!CModule::IncludeModule("sale")) {
- //handler
- }
-
- if (isset($_POST['back']) && $_POST['back']) {
- $APPLICATION->IncludeAdminFile(
- GetMessage('MODULE_INSTALL_TITLE'),
- $_SERVER['DOCUMENT_ROOT'] . '/bitrix/modules/' . $this->MODULE_ID . '/install/step1.php'
- );
- }
-
- // api load
- $api_host = COption::GetOptionString($this->MODULE_ID, $this->CRM_API_HOST_OPTION, 0);
- $api_key = COption::GetOptionString($this->MODULE_ID, $this->CRM_API_KEY_OPTION, 0);
- $this->INTARO_CRM_API = new \IntaroCrm\RestApi($api_host, $api_key);
-
- //bitrix orderTypesList -- personTypes
- $dbOrderTypesList = CSalePersonType::GetList(
- array(
- "SORT" => "ASC",
- "NAME" => "ASC"
- ), array(
- "ACTIVE" => "Y",
- ), false, false, array()
- );
-
- //form order types ids arr
- $orderTypesArr = array();
- $arResult['bitrixOrderTypesList'] = array();
- if ($arOrderTypesList = $dbOrderTypesList->Fetch()) {
- do {
- $orderTypesArr[$arOrderTypesList['ID']] = htmlspecialchars(trim($_POST['order-type-' . $arOrderTypesList['ID']]));
- $arResult['bitrixOrderTypesList'][] = $arOrderTypesList;
- } while ($arOrderTypesList = $dbOrderTypesList->Fetch());
- }
-
- //bitrix deliveryTypesList
- $dbDeliveryTypesList = CSaleDelivery::GetList(
- array(
- "SORT" => "ASC",
- "NAME" => "ASC"
- ), array(
- "ACTIVE" => "Y",
- ), false, false, array()
- );
-
- //form delivery types ids arr
- $deliveryTypesArr = array();
-
- if (htmlspecialchars(trim($_POST['delivery-types-export'])) == 'false') {
- if ($arDeliveryTypesList = $dbDeliveryTypesList->Fetch()) {
- do {
- $deliveryTypesArr[$arDeliveryTypesList['ID']] = htmlspecialchars(trim($_POST['delivery-type-' . $arDeliveryTypesList['ID']]));
- } while ($arDeliveryTypesList = $dbDeliveryTypesList->Fetch());
- }
- } elseif (htmlspecialchars(trim($_POST['delivery-types-export'])) == 'true') {
- // send to intaro crm and save
- if ($arDeliveryTypesList = $dbDeliveryTypesList->Fetch()) {
- do {
- // parse id
- $arId = array();
- $resultDeliveryTypeId = 0;
- if (strpos($arDeliveryTypesList['ID'], ":") !== false)
- $arId = explode(":", $arDeliveryTypesList['ID']);
-
- if ($arId)
- $resultDeliveryTypeId = $arId[0];
- else
- $resultDeliveryTypeId = $arDeliveryTypesList['ID'];
-
- $deliveryTypesArr[$arDeliveryTypesList['ID']] = $resultDeliveryTypeId;
-
- // send to crm
- $this->INTARO_CRM_API->deliveryTypeEdit(ICrmOrderActions::clearArr(array(
- 'code' => $resultDeliveryTypeId,
- 'name' => ICrmOrderActions::toJSON($arDeliveryTypesList['NAME']),
- 'defaultCost' => $arDeliveryTypesList['PRICE'],
- 'description' => ICrmOrderActions::toJSON($arDeliveryTypesList['DESCRIPTION']),
- 'paymentTypes' => ''
- )));
-
- // error pushing customer
- if ($this->INTARO_CRM_API->getStatusCode() != 200) {
- if ($this->INTARO_CRM_API->getStatusCode() != 201) {
- //handle err
- ICrmOrderActions::eventLog('install/index.php', 'IntaroCrm\RestApi::deliveryTypeEdit', $this->INTARO_CRM_API->getLastError());
- }
- }
- } while ($arDeliveryTypesList = $dbDeliveryTypesList->Fetch());
- }
- }
-
- //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']] = 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"
- )
- );
-
- //form payment statuses ids arr
- $paymentStatusesArr['YY'] = htmlspecialchars(trim($_POST['payment-status-YY']));
-
- if ($arPaymentStatusesList = $dbPaymentStatusesList->Fetch()) {
- do {
- $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']));
-
- //form orderProps
- $dbProp = CSaleOrderProps::GetList(array(), array());
- while ($arProp = $dbProp->GetNext()) {
- $arResult['arProp'][$arProp['PERSON_TYPE_ID']][] = $arProp;
- }
-
- 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_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);
- COption::SetOptionString($this->MODULE_ID, $this->CRM_ORDER_DISCHARGE, 0);
- COption::SetOptionString($this->MODULE_ID, $this->CRM_ORDER_FAILED_IDS, serialize(array()));
- COption::SetOptionString($this->MODULE_ID, $this->CRM_ORDER_HISTORY_DATE, date('Y-m-d H:i:s'));
-
- $APPLICATION->IncludeAdminFile(
- GetMessage('MODULE_INSTALL_TITLE'),
- $_SERVER['DOCUMENT_ROOT'] . '/bitrix/modules/' . $this->MODULE_ID . '/install/step3.php'
- );
- } else if ($step == 4) {
- if (!CModule::IncludeModule("sale")) {
- //handler
- }
-
- if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && (strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest')
- && isset($_POST['ajax']) && ($_POST['ajax'] == 1)) {
- ICrmOrderActions::uploadOrders(); // each 50
-
- $lastUpOrderId = COption::GetOptionString($this->MODULE_ID, $this->CRM_ORDER_LAST_ID, 0);
- $countLeft = (int) CSaleOrder::GetList(array("ID" => "ASC"), array('>ID' => $lastUpOrderId), array());
- $countAll = (int) CSaleOrder::GetList(array("ID" => "ASC"), array(), array());
-
- if (!isset($_POST['finish']))
- $finish = 0;
- else
- $finish = (int) $_POST['finish'];
-
- $percent = round(100 - ($countLeft * 100 / $countAll), 1);
-
- if (!$countLeft)
- $finish = 1;
-
- $APPLICATION->RestartBuffer();
- header('Content-Type: application/x-javascript; charset=' . LANG_CHARSET);
- die(json_encode(array("finish" => $finish, "percent" => $percent)));
- }
-
- if (isset($_POST['back']) && $_POST['back']) {
- $APPLICATION->IncludeAdminFile(
- GetMessage('MODULE_INSTALL_TITLE'), $_SERVER['DOCUMENT_ROOT'] . '/bitrix/modules/' . $this->MODULE_ID . '/install/step2.php'
- );
- }
-
- //bitrix orderTypesList -- personTypes
- $dbOrderTypesList = CSalePersonType::GetList(
- array(
- "SORT" => "ASC",
- "NAME" => "ASC"
- ), array(
- "ACTIVE" => "Y",
- ), false, false, array()
- );
-
- //form order types ids arr
- $orderTypesArr = array();
- $orderTypesList = array();
- if ($arOrderTypesList = $dbOrderTypesList->Fetch()) {
- do {
- $orderTypesArr[$arOrderTypesList['ID']] = htmlspecialchars(trim($_POST['order-type-' . $arOrderTypesList['ID']]));
- $orderTypesList[] = $arOrderTypesList;
- } while ($arOrderTypesList = $dbOrderTypesList->Fetch());
- }
-
- $orderPropsArr = array();
- foreach ($orderTypesList as $orderType) {
- $propsCount = 0;
- $_orderPropsArr = array();
- foreach ($arResult['orderProps'] as $orderProp) {
- if ((!(int) htmlspecialchars(trim($_POST['address-detail-' . $orderType['ID']]))) && $propsCount > 4)
- break;
- $_orderPropsArr[$orderProp['ID']] = htmlspecialchars(trim($_POST['order-prop-' . $orderProp['ID'] . '-' . $orderType['ID']]));
- $propsCount++;
- }
- $orderPropsArr[$orderType['ID']] = $_orderPropsArr;
- }
-
- COption::SetOptionString($this->MODULE_ID, $this->CRM_ORDER_PROPS, serialize($orderPropsArr));
-
- $APPLICATION->IncludeAdminFile(
- GetMessage('MODULE_INSTALL_TITLE'),
- $_SERVER['DOCUMENT_ROOT'] . '/bitrix/modules/' . $this->MODULE_ID . '/install/step4.php'
- );
-
- } else if ($step == 5) {
- if (!CModule::IncludeModule("iblock")) {
- $arResult['errCode'] = 'ERR_IBLOCK';
- }
-
- if (!CModule::IncludeModule("catalog")) {
- $arResult['errCode'] = 'ERR_CATALOG';
- }
- $APPLICATION->IncludeAdminFile(
- GetMessage('MODULE_INSTALL_TITLE'),
- $_SERVER['DOCUMENT_ROOT'] . '/bitrix/modules/' . $this->MODULE_ID . '/install/step5.php'
- );
- } else if ($step == 6) {
-
- if (!CModule::IncludeModule("iblock")) {
- $arResult['errCode'] = 'ERR_IBLOCK';
- }
-
- if (!CModule::IncludeModule("catalog")) {
- $arResult['errCode'] = 'ERR_CATALOG';
- }
-
- if (isset($arResult['errCode']) && $arResult['errCode']) {
- $APPLICATION->IncludeAdminFile(
- GetMessage('MODULE_INSTALL_TITLE'),
- $_SERVER['DOCUMENT_ROOT'] . '/bitrix/modules/' . $this->MODULE_ID . '/install/step5.php'
- );
- return;
- }
-
- if (isset($_POST['back']) && $_POST['back']) {
- $APPLICATION->IncludeAdminFile(
- GetMessage('MODULE_INSTALL_TITLE'),
- $_SERVER['DOCUMENT_ROOT'] . '/bitrix/modules/' . $this->MODULE_ID . '/install/step3.php'
- );
- }
-
- if (!isset($_POST['IBLOCK_EXPORT']))
- $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['SETUP_FILE_NAME']))
- $arResult['errCode'] = 'ERR_FIELDS_FILE';
- else
- $filename = $_POST['SETUP_FILE_NAME'];
-
- if (!isset($_POST['TYPE_LOADING']))
- $typeLoading = 0;
- else
- $typeLoading = $_POST['TYPE_LOADING'];
-
- if (!isset($_POST['SETUP_PROFILE_NAME']))
- $profileName = "";
- else
- $profileName = $_POST['SETUP_PROFILE_NAME'];
-
- if ($typeLoading != 'none' && $profileName == "")
- $arResult['errCode'] = 'ERR_FIELDS_PROFILE';
-
- if ($filename == "")
- $arResult['errCode'] = 'ERR_FIELDS_FILE';
-
- if (isset($arResult['errCode']) && $arResult['errCode']) {
-
- $arOldValues = Array(
- 'IBLOCK_EXPORT' => $iblocks,
- 'IBLOCK_PROPERTY_SKU' => $propertiesSKU,
- 'IBLOCK_PROPERTY_PRODUCT' => $propertiesProduct,
- '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'
- );
- return;
- }
-
- RegisterModule($this->MODULE_ID);
- RegisterModuleDependences("sale", "OnSalePayOrder", $this->MODULE_ID, "ICrmOrderEvent", "onSalePayOrder");
- RegisterModuleDependences("sale", "OnSaleCancelOrder", $this->MODULE_ID, "ICrmOrderEvent", "onSaleCancelOrder");
- $this->CopyFiles();
- if (isset($_POST['LOAD_NOW'])) {
-
- $loader = new ICMLLoader();
- $loader->iblocks = $iblocks;
- $loader->propertiesProduct = $propertiesProduct;
- $loader->propertiesSKU = $propertiesSKU;
- $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));
-
- while ($arProfile = $dbProfile->Fetch()) {
- if ($arProfile["DEFAULT_PROFILE"] != "Y") {
- CAgent::RemoveAgent("CCatalogExport::PreGenerateExport(" . $arProfile['ID'] . ");", "catalog");
- CCatalogExport::Delete($arProfile['ID']);
- }
- }
- }
- $ar = $this->GetProfileSetupVars($iblocks, $propertiesProduct, $propertiesSKU, $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
- ));
- if (intval($PROFILE_ID) <= 0) {
- $arResult['errCode'] = 'ERR_IBLOCK';
- return;
- }
- if ($typeLoading == 'agent') {
-
- $dateAgent = new DateTime();
- $intAgent = new DateInterval('PT60S'); // PT60S - 60 sec;
- $dateAgent->add($intAgent);
- CAgent::AddAgent(
- "CCatalogExport::PreGenerateExport(" . $PROFILE_ID . ");", "catalog", "N", 86400, $dateAgent->format('d.m.Y H:i:s'), // date of first check
- "Y", // agent is active
- $dateAgent->format('d.m.Y H:i:s'), // date of first start
- 30
- );
-
- CCatalogExport::Update($PROFILE_ID, array(
- "IN_AGENT" => "Y"
- ));
- } else {
- $agent_period = 24;
- $agent_php_path = "/usr/local/php/bin/php";
-
- if (!file_exists($_SERVER["DOCUMENT_ROOT"] . CATALOG_PATH2EXPORTS . "cron_frame.php")) {
- CheckDirPath($_SERVER["DOCUMENT_ROOT"] . CATALOG_PATH2EXPORTS);
- $tmp_file_size = filesize($_SERVER["DOCUMENT_ROOT"] . CATALOG_PATH2EXPORTS_DEF . "cron_frame.php");
- $fp = fopen($_SERVER["DOCUMENT_ROOT"] . CATALOG_PATH2EXPORTS_DEF . "cron_frame.php", "rb");
- $tmp_data = fread($fp, $tmp_file_size);
- fclose($fp);
-
- $tmp_data = str_replace("#DOCUMENT_ROOT#", $_SERVER["DOCUMENT_ROOT"], $tmp_data);
- $tmp_data = str_replace("#PHP_PATH#", $agent_php_path, $tmp_data);
-
- $fp = fopen($_SERVER["DOCUMENT_ROOT"] . CATALOG_PATH2EXPORTS . "cron_frame.php", "ab");
- fwrite($fp, $tmp_data);
- fclose($fp);
- }
-
- $cfg_data = "";
- if (file_exists($_SERVER["DOCUMENT_ROOT"] . "/bitrix/crontab/crontab.cfg")) {
- $cfg_file_size = filesize($_SERVER["DOCUMENT_ROOT"] . "/bitrix/crontab/crontab.cfg");
- $fp = fopen($_SERVER["DOCUMENT_ROOT"] . "/bitrix/crontab/crontab.cfg", "rb");
- $cfg_data = fread($fp, $cfg_file_size);
- fclose($fp);
- }
-
- CheckDirPath($_SERVER["DOCUMENT_ROOT"] . CATALOG_PATH2EXPORTS . "logs/");
-
- if ($arProfile["IN_CRON"] == "Y") {
- // remove
- $cfg_data = preg_replace("#^.*?" . preg_quote(CATALOG_PATH2EXPORTS) . "cron_frame.php +" . $PROFILE_ID . " *>.*?$#im", "", $cfg_data);
- } else {
- $strTime = "0 */" . $agent_period . " * * * ";
- if (strlen($cfg_data) > 0)
- $cfg_data .= "\n";
-
- $cfg_data .= $strTime . $agent_php_path . " -f " . $_SERVER["DOCUMENT_ROOT"] . CATALOG_PATH2EXPORTS . "cron_frame.php " . $PROFILE_ID . " >" . $_SERVER["DOCUMENT_ROOT"] . CATALOG_PATH2EXPORTS . "logs/" . $PROFILE_ID . ".txt\n";
- }
-
- CCatalogExport::Update($PROFILE_ID, array(
- "IN_CRON" => "Y"
- ));
-
- CheckDirPath($_SERVER["DOCUMENT_ROOT"] . "/bitrix/crontab/");
- $cfg_data = preg_replace("#[\r\n]{2,}#im", "\n", $cfg_data);
- $fp = fopen($_SERVER["DOCUMENT_ROOT"] . "/bitrix/crontab/crontab.cfg", "wb");
- fwrite($fp, $cfg_data);
- fclose($fp);
-
- $arRetval = array();
- @exec("crontab " . $_SERVER["DOCUMENT_ROOT"] . "/bitrix/crontab/crontab.cfg", $arRetval, $return_var);
- }
- }
-
- //agent
-
- $dateAgent = new DateTime();
- $intAgent = new DateInterval('PT60S'); // PT60S - 60 sec;
- $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", // agent is active
- $dateAgent->format('d.m.Y H:i:s'), // date of first start
- 30
- );
-
- CAgent::AddAgent(
- "ICrmOrderActions::orderHistoryAgent();",
- $this->MODULE_ID,
- "N",
- 600, // interval - 10 mins
- $dateAgent->format('d.m.Y H:i:s'), // date of first check
- "Y", // agent is active
- $dateAgent->format('d.m.Y H:i:s'), // date of first start
- 30
- );
-
- $api_host = COption::GetOptionString($this->MODULE_ID, $this->CRM_API_HOST_OPTION, 0);
- $api_key = COption::GetOptionString($this->MODULE_ID, $this->CRM_API_KEY_OPTION, 0);
- $this->INTARO_CRM_API = new \IntaroCrm\RestApi($api_host, $api_key);
- $this->INTARO_CRM_API->statisticUpdate();
-
- $APPLICATION->IncludeAdminFile(
- GetMessage('MODULE_INSTALL_TITLE'),
- $_SERVER['DOCUMENT_ROOT'] . '/bitrix/modules/' . $this->MODULE_ID . '/install/step6.php'
- );
- }
- }
-
- function DoUninstall() {
- global $APPLICATION;
-
- CAgent::RemoveAgent("ICrmOrderActions::uploadOrdersAgent();", $this->MODULE_ID);
- CAgent::RemoveAgent("ICrmOrderActions::orderHistoryAgent();", $this->MODULE_ID);
-
- COption::RemoveOption($this->MODULE_ID, $this->CRM_API_HOST_OPTION);
- COption::RemoveOption($this->MODULE_ID, $this->CRM_API_KEY_OPTION);
- 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);
- COption::RemoveOption($this->MODULE_ID, $this->CRM_ORDER_LAST_ID);
- COption::RemoveOption($this->MODULE_ID, $this->CRM_ORDER_SITES);
- COption::RemoveOption($this->MODULE_ID, $this->CRM_ORDER_PROPS);
- COption::RemoveOption($this->MODULE_ID, $this->CRM_ORDER_DISCHARGE);
- COption::RemoveOption($this->MODULE_ID, $this->CRM_ORDER_FAILED_IDS);
- COption::RemoveOption($this->MODULE_ID, $this->CRM_ORDER_HISTORY_DATE);
-
- UnRegisterModuleDependences("sale", "OnSalePayOrder", $this->MODULE_ID, "ICrmOrderEvent", "onSalePayOrder");
- UnRegisterModuleDependences("sale", "OnSaleCancelOrder", $this->MODULE_ID, "ICrmOrderEvent", "onSaleCancelOrder");
- UnRegisterModuleDependences("sale", "OnOrderNewSendEmail", $this->MODULE_ID, "ICrmOrderEvent", "onSendOrderMail");
- UnRegisterModuleDependences("sale", "OnOrderUpdate", $this->MODULE_ID, "ICrmOrderEvent", "onUpdateOrder");
- UnRegisterModuleDependences("sale", "OnBeforeOrderAdd", $this->MODULE_ID, "ICrmOrderEvent", "onBeforeOrderAdd");
- if (CModule::IncludeModule("catalog")) {
- 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));
-
- while ($arProfile = $dbProfile->Fetch()) {
- if ($arProfile["DEFAULT_PROFILE"] != "Y") {
- CAgent::RemoveAgent("CCatalogExport::PreGenerateExport(" . $arProfile['ID'] . ");", "catalog");
- CCatalogExport::Delete($arProfile['ID']);
- }
- }
- }
- }
-
- $this->DeleteFiles();
-
- UnRegisterModule($this->MODULE_ID);
-
- $APPLICATION->IncludeAdminFile(
- GetMessage('MODULE_UNINSTALL_TITLE'), $_SERVER['DOCUMENT_ROOT'] . '/bitrix/modules/' . $this->MODULE_ID . '/install/unstep1.php'
- );
- }
-
- function CopyFiles() {
- CopyDirFiles(
- $_SERVER['DOCUMENT_ROOT'] . '/bitrix/modules/' . $this->MODULE_ID . '/install/export/', $_SERVER['DOCUMENT_ROOT'] . '/bitrix/php_interface/include/catalog_export/', true, true
- );
- }
-
- function DeleteFiles() {
- unlink($_SERVER['DOCUMENT_ROOT'] . '/bitrix/php_interface/include/catalog_export/intarocrm_run.php');
- unlink($_SERVER['DOCUMENT_ROOT'] . '/bitrix/php_interface/include/catalog_export/intarocrm_setup.php');
- }
-
- function GetProfileSetupVars($iblocks, $propertiesProduct, $propertiesSKU, $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)
- $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 . '&';
-
- $strVars .= 'SETUP_FILE_NAME=' . urlencode($filename);
-
- return $strVars;
- }
+INSTALL_PATH = $path;
+ include($path . "/version.php");
+ $this->MODULE_VERSION = $arModuleVersion["VERSION"];
+ $this->MODULE_VERSION_DATE = $arModuleVersion["VERSION_DATE"];
+ $this->MODULE_NAME = GetMessage('MODULE_NAME');
+ $this->MODULE_DESCRIPTION = GetMessage('MODULE_DESCRIPTION');
+ $this->PARTNER_NAME = GetMessage('MODULE_PARTNER_NAME');
+ $this->PARTNER_URI = GetMessage('MODULE_PARTNER_URI');
+ }
+
+ /**
+ * Functions DoInstall and DoUninstall are
+ * All other functions are optional
+ */
+ function DoInstall() {
+ global $APPLICATION, $step, $arResult;
+
+ if (!in_array('curl', get_loaded_extensions())) {
+ $APPLICATION->ThrowException(GetMessage("INTAROCRM_CURL_ERR"));
+ return false;
+ }
+
+ if (!date_default_timezone_get()) {
+ if (!ini_get('date.timezone')) {
+ $APPLICATION->ThrowException(GetMessage("DATE_TIMEZONE_ERR"));
+ return false;
+ }
+ }
+
+ include($this->INSTALL_PATH . '/../classes/general/RestApi.php');
+ include($this->INSTALL_PATH . '/../classes/general/ICrmOrderActions.php');
+ include($this->INSTALL_PATH . '/../classes/general/ICMLLoader.php');
+
+ $step = intval($_REQUEST['step']);
+
+ $arResult['orderProps'] = array(
+ array(
+ 'NAME' => GetMessage('FIO'),
+ 'ID' => 'fio'
+ ),
+ array(
+ 'NAME' => GetMessage('PHONE'),
+ 'ID' => 'phone'
+ ),
+ array(
+ 'NAME' => GetMessage('EMAIL'),
+ 'ID' => 'email'
+ ),
+ array(
+ 'NAME' => GetMessage('ADDRESS'),
+ 'ID' => 'text'
+ ),
+ // address
+ /* array(
+ 'NAME' => GetMessage('COUNTRY'),
+ 'ID' => 'country'
+ ),
+ array(
+ 'NAME' => GetMessage('REGION'),
+ 'ID' => 'region'
+ ),
+ array(
+ 'NAME' => GetMessage('CITY'),
+ 'ID' => 'city'
+ ), */
+ array(
+ 'NAME' => GetMessage('ZIP'),
+ 'ID' => 'index'
+ ),
+ array(
+ 'NAME' => GetMessage('STREET'),
+ 'ID' => 'street'
+ ),
+ array(
+ 'NAME' => GetMessage('BUILDING'),
+ 'ID' => 'building'
+ ),
+ array(
+ 'NAME' => GetMessage('FLAT'),
+ 'ID' => 'flat'
+ ),
+ array(
+ 'NAME' => GetMessage('INTERCOMCODE'),
+ 'ID' => 'intercomcode'
+ ),
+ array(
+ 'NAME' => GetMessage('FLOOR'),
+ 'ID' => 'floor'
+ ),
+ array(
+ 'NAME' => GetMessage('BLOCK'),
+ 'ID' => 'block'
+ ),
+ array(
+ 'NAME' => GetMessage('HOUSE'),
+ 'ID' => 'house'
+ )
+ );
+
+ if ($step <= 1) {
+ if (!CModule::IncludeModule("sale")) {
+ $arResult['errCode'] = 'ERR_SALE';
+ }
+
+ if (!CModule::IncludeModule("iblock")) {
+ $arResult['errCode'] = 'ERR_IBLOCK';
+ }
+
+ if (!CModule::IncludeModule("catalog")) {
+ $arResult['errCode'] = 'ERR_CATALOG';
+ }
+
+ $arResult['arSites'] = array();
+ $rsSites = CSite::GetList($by, $sort, array());
+ while ($ar = $rsSites->Fetch())
+ $arResult['arSites'][] = $ar;
+
+ $APPLICATION->IncludeAdminFile(
+ GetMessage('MODULE_INSTALL_TITLE'), $_SERVER['DOCUMENT_ROOT'] . '/bitrix/modules/' . $this->MODULE_ID . '/install/step1.php'
+ );
+ } else if ($step == 2) {
+
+ if (!CModule::IncludeModule("sale")) {
+ $arResult['errCode'] = 'ERR_SALE';
+ }
+
+ if (!CModule::IncludeModule("iblock")) {
+ $arResult['errCode'] = 'ERR_IBLOCK';
+ }
+
+ if (!CModule::IncludeModule("catalog")) {
+ $arResult['errCode'] = 'ERR_CATALOG';
+ }
+
+ $arResult['arSites'] = array();
+ $rsSites = CSite::GetList($by, $sort, array());
+ while ($ar = $rsSites->Fetch())
+ $arResult['arSites'][] = $ar;
+
+ if (isset($arResult['errCode']) && $arResult['errCode']) {
+ $APPLICATION->IncludeAdminFile(
+ GetMessage('MODULE_INSTALL_TITLE'),
+ $_SERVER['DOCUMENT_ROOT'] . '/bitrix/modules/' . $this->MODULE_ID . '/install/step1.php'
+ );
+ return;
+ }
+
+ if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && (strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') && isset($_POST['ajax']) && ($_POST['ajax'] == 1)) {
+
+ $api_host = COption::GetOptionString($this->MODULE_ID, $this->CRM_API_HOST_OPTION, 0);
+ $api_key = COption::GetOptionString($this->MODULE_ID, $this->CRM_API_KEY_OPTION, 0);
+ $this->INTARO_CRM_API = new \IntaroCrm\RestApi($api_host, $api_key);
+
+ //prepare crm lists
+ $arResult['orderTypesList'] = $this->INTARO_CRM_API->orderTypesList();
+
+ if ((int) $this->INTARO_CRM_API->getStatusCode() != 200) {
+ $APPLICATION->RestartBuffer();
+ header('Content-Type: application/x-javascript; charset=' . LANG_CHARSET);
+ die(json_encode(array("success" => false)));
+ }
+
+ $arResult['deliveryTypesList'] = $this->INTARO_CRM_API->deliveryTypesList();
+ $arResult['paymentTypesList'] = $this->INTARO_CRM_API->paymentTypesList();
+ $arResult['paymentStatusesList'] = $this->INTARO_CRM_API->paymentStatusesList(); // --statuses
+ $arResult['paymentList'] = $this->INTARO_CRM_API->orderStatusesList();
+ $arResult['paymentGroupList'] = $this->INTARO_CRM_API->orderStatusGroupsList(); // -- statuses groups
+ //bitrix orderTypesList -- personTypes
+ $dbOrderTypesList = CSalePersonType::GetList(
+ array(
+ "SORT" => "ASC",
+ "NAME" => "ASC"
+ ), array(
+ "ACTIVE" => "Y",
+ ), false, false, array()
+ );
+
+
+ //form order types ids arr
+ $orderTypesArr = array();
+ if ($arOrderTypesList = $dbOrderTypesList->Fetch()) {
+ do {
+ $arResult['bitrixOrderTypesList'][] = $arOrderTypesList;
+ $orderTypesArr[$arOrderTypesList['ID']] = htmlspecialchars(trim($_POST['order-type-' . $arOrderTypesList['ID']]));
+ } while ($arOrderTypesList = $dbOrderTypesList->Fetch());
+ }
+
+ //bitrix deliveryTypesList
+ $dbDeliveryTypesList = CSaleDelivery::GetList(
+ array(
+ "SORT" => "ASC",
+ "NAME" => "ASC"
+ ), array(
+ "ACTIVE" => "Y",
+ ), false, false, array()
+ );
+
+ //form delivery types ids arr
+ $deliveryTypesArr = array();
+ if ($arDeliveryTypesList = $dbDeliveryTypesList->Fetch()) {
+ do {
+ $arResult['bitrixDeliveryTypesList'][] = $arDeliveryTypesList;
+ $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"
+ )
+ );
+
+ //form payment types ids arr
+ $paymentTypesArr = array();
+ if ($arPaymentTypesList = $dbPaymentTypesList->Fetch()) {
+ do {
+ $arResult['bitrixPaymentTypesList'][] = $arPaymentTypesList;
+ $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"
+ )
+ );
+
+ //form payment statuses ids arr
+ $paymentStatusesArr['YY'] = htmlspecialchars(trim($_POST['payment-status-YY']));
+ if ($arPaymentStatusesList = $dbPaymentStatusesList->Fetch()) {
+ do {
+ $arResult['bitrixPaymentStatusesList'][] = $arPaymentStatusesList;
+ $paymentStatusesArr[$arPaymentStatusesList['ID']] = htmlspecialchars(trim($_POST['payment-status-' . $arPaymentStatusesList['ID']]));
+ } while ($arPaymentStatusesList = $dbPaymentStatusesList->Fetch());
+ }
+
+ $arResult['bitrixPaymentStatusesList'][] = array(
+ 'ID' => 'YY',
+ 'NAME' => GetMessage('CANCELED')
+ );
+
+ //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_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));
+
+ // generate updated select inputs
+ $input = array();
+
+ foreach ($arResult['bitrixDeliveryTypesList'] as $bitrixDeliveryType) {
+ $input['delivery-type-' . $bitrixDeliveryType['ID']] =
+ '';
+ }
+
+ foreach ($arResult['bitrixPaymentTypesList'] as $bitrixPaymentType) {
+ $input['payment-type-' . $bitrixPaymentType['ID']] =
+ '';
+ }
+
+ foreach ($arResult['bitrixPaymentStatusesList'] as $bitrixPaymentStatus) {
+ $input['payment-status-' . $bitrixPaymentStatus['ID']] =
+ '';
+ }
+
+ foreach ($arResult['bitrixPaymentList'] as $bitrixPayment) {
+ $input['payment-' . $bitrixPayment['ID']] =
+ '';
+ }
+
+ foreach ($arResult['bitrixOrderTypesList'] as $bitrixOrderType) {
+ $input['order-type-' . $bitrixOrderType['ID']] =
+ '';
+ }
+
+ $APPLICATION->RestartBuffer();
+ header('Content-Type: application/x-javascript; charset=' . LANG_CHARSET);
+ die(json_encode(array("success" => true, "result" => $input)));
+ }
+
+ $api_host = htmlspecialchars(trim($_POST[$this->CRM_API_HOST_OPTION]));
+ $api_key = htmlspecialchars(trim($_POST[$this->CRM_API_KEY_OPTION]));
+
+ // empty == select all
+ $orderSites = array();
+ foreach ($_POST[$this->CRM_ORDER_SITES] as $site) {
+ $orderSites[] = htmlspecialchars(trim($site));
+ }
+
+ // 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) {
+ $arResult['errCode'] = 'ERR_FIELDS_API_HOST';
+ $APPLICATION->IncludeAdminFile(
+ GetMessage('MODULE_INSTALL_TITLE'),
+ $_SERVER['DOCUMENT_ROOT'] . '/bitrix/modules/' . $this->MODULE_ID . '/install/step1.php'
+ );
+ return;
+ }
+
+ $this->INTARO_CRM_API = new \IntaroCrm\RestApi($api_host, $api_key);
+
+ $this->INTARO_CRM_API->paymentStatusesList();
+
+ //check connection & apiKey valid
+ if ((int) $this->INTARO_CRM_API->getStatusCode() != 200) {
+ $arResult['errCode'] = 'ERR_' . $this->INTARO_CRM_API->getStatusCode();
+
+ $APPLICATION->IncludeAdminFile(
+ GetMessage('MODULE_INSTALL_TITLE'),
+ $_SERVER['DOCUMENT_ROOT'] . '/bitrix/modules/' . $this->MODULE_ID . '/install/step1.php'
+ );
+
+ return;
+ }
+
+ COption::SetOptionString($this->MODULE_ID, $this->CRM_API_HOST_OPTION, $api_host);
+ COption::SetOptionString($this->MODULE_ID, $this->CRM_API_KEY_OPTION, $api_key);
+ COption::SetOptionString($this->MODULE_ID, $this->CRM_ORDER_SITES, serialize($orderSites));
+
+ //prepare crm lists
+ $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(); // --statuses
+ $arResult['paymentList'] = $this->INTARO_CRM_API->orderStatusesList();
+ $arResult['paymentGroupList'] = $this->INTARO_CRM_API->orderStatusGroupsList(); // -- statuses groups
+ //bitrix orderTypesList -- personTypes
+ $dbOrderTypesList = CSalePersonType::GetList(
+ array(
+ "SORT" => "ASC",
+ "NAME" => "ASC"
+ ), array(
+ "ACTIVE" => "Y",
+ ), false, false, array()
+ );
+
+ if ($arOrderTypesList = $dbOrderTypesList->Fetch()) {
+ do {
+ $arResult['bitrixOrderTypesList'][] = $arOrderTypesList;
+ } while ($arOrderTypesList = $dbOrderTypesList->Fetch());
+ }
+
+ //bitrix deliveryTypesList
+ $dbDeliveryTypesList = CSaleDelivery::GetList(
+ array(
+ "SORT" => "ASC",
+ "NAME" => "ASC"
+ ), array(
+ "ACTIVE" => "Y",
+ ), false, false, array()
+ );
+
+ if ($arDeliveryTypesList = $dbDeliveryTypesList->Fetch()) {
+ do {
+ $arResult['bitrixDeliveryTypesList'][] = $arDeliveryTypesList;
+ } while ($arDeliveryTypesList = $dbDeliveryTypesList->Fetch());
+ }
+
+ //bitrix paymentTypesList
+ $dbPaymentTypesList = CSalePaySystem::GetList(
+ array(
+ "SORT" => "ASC",
+ "NAME" => "ASC"
+ ), array(
+ "ACTIVE" => "Y"
+ )
+ );
+
+ if ($arPaymentTypesList = $dbPaymentTypesList->Fetch()) {
+ do {
+ $arResult['bitrixPaymentTypesList'][] = $arPaymentTypesList;
+ } while ($arPaymentTypesList = $dbPaymentTypesList->Fetch());
+ }
+
+ //bitrix paymentStatusesList --statuses
+ $dbPaymentStatusesList = CSaleStatus::GetList(
+ array(
+ "SORT" => "ASC",
+ "NAME" => "ASC"
+ ), array(
+ "LID" => "ru", //ru
+ "ACTIVE" => "Y"
+ )
+ );
+
+ if ($arPaymentStatusesList = $dbPaymentStatusesList->Fetch()) {
+ do {
+ $arResult['bitrixPaymentStatusesList'][] = $arPaymentStatusesList;
+ } while ($arPaymentStatusesList = $dbPaymentStatusesList->Fetch());
+ }
+
+ $arResult['bitrixPaymentStatusesList'][] = array(
+ 'ID' => 'YY',
+ 'NAME' => GetMessage('CANCELED')
+ );
+
+ $APPLICATION->IncludeAdminFile(
+ GetMessage('MODULE_INSTALL_TITLE'),
+ $_SERVER['DOCUMENT_ROOT'] . '/bitrix/modules/' . $this->MODULE_ID . '/install/step2.php'
+ );
+ } else if ($step == 3) {
+ if (!CModule::IncludeModule("sale")) {
+ //handler
+ }
+
+ if (isset($_POST['back']) && $_POST['back']) {
+ $APPLICATION->IncludeAdminFile(
+ GetMessage('MODULE_INSTALL_TITLE'),
+ $_SERVER['DOCUMENT_ROOT'] . '/bitrix/modules/' . $this->MODULE_ID . '/install/step1.php'
+ );
+ }
+
+ // api load
+ $api_host = COption::GetOptionString($this->MODULE_ID, $this->CRM_API_HOST_OPTION, 0);
+ $api_key = COption::GetOptionString($this->MODULE_ID, $this->CRM_API_KEY_OPTION, 0);
+ $this->INTARO_CRM_API = new \IntaroCrm\RestApi($api_host, $api_key);
+
+ //bitrix orderTypesList -- personTypes
+ $dbOrderTypesList = CSalePersonType::GetList(
+ array(
+ "SORT" => "ASC",
+ "NAME" => "ASC"
+ ), array(
+ "ACTIVE" => "Y",
+ ), false, false, array()
+ );
+
+ //form order types ids arr
+ $orderTypesArr = array();
+ $arResult['bitrixOrderTypesList'] = array();
+ if ($arOrderTypesList = $dbOrderTypesList->Fetch()) {
+ do {
+ $orderTypesArr[$arOrderTypesList['ID']] = htmlspecialchars(trim($_POST['order-type-' . $arOrderTypesList['ID']]));
+ $arResult['bitrixOrderTypesList'][] = $arOrderTypesList;
+ } while ($arOrderTypesList = $dbOrderTypesList->Fetch());
+ }
+
+ //bitrix deliveryTypesList
+ $dbDeliveryTypesList = CSaleDelivery::GetList(
+ array(
+ "SORT" => "ASC",
+ "NAME" => "ASC"
+ ), array(
+ "ACTIVE" => "Y",
+ ), false, false, array()
+ );
+
+ //form delivery types ids arr
+ $deliveryTypesArr = array();
+
+ if (htmlspecialchars(trim($_POST['delivery-types-export'])) == 'false') {
+ if ($arDeliveryTypesList = $dbDeliveryTypesList->Fetch()) {
+ do {
+ $deliveryTypesArr[$arDeliveryTypesList['ID']] = htmlspecialchars(trim($_POST['delivery-type-' . $arDeliveryTypesList['ID']]));
+ } while ($arDeliveryTypesList = $dbDeliveryTypesList->Fetch());
+ }
+ } elseif (htmlspecialchars(trim($_POST['delivery-types-export'])) == 'true') {
+ // send to intaro crm and save
+ if ($arDeliveryTypesList = $dbDeliveryTypesList->Fetch()) {
+ do {
+ // parse id
+ $arId = array();
+ $resultDeliveryTypeId = 0;
+ if (strpos($arDeliveryTypesList['ID'], ":") !== false)
+ $arId = explode(":", $arDeliveryTypesList['ID']);
+
+ if ($arId)
+ $resultDeliveryTypeId = $arId[0];
+ else
+ $resultDeliveryTypeId = $arDeliveryTypesList['ID'];
+
+ $deliveryTypesArr[$arDeliveryTypesList['ID']] = $resultDeliveryTypeId;
+
+ // send to crm
+ $this->INTARO_CRM_API->deliveryTypeEdit(ICrmOrderActions::clearArr(array(
+ 'code' => $resultDeliveryTypeId,
+ 'name' => ICrmOrderActions::toJSON($arDeliveryTypesList['NAME']),
+ 'defaultCost' => $arDeliveryTypesList['PRICE'],
+ 'description' => ICrmOrderActions::toJSON($arDeliveryTypesList['DESCRIPTION']),
+ 'paymentTypes' => ''
+ )));
+
+ // error pushing customer
+ if ($this->INTARO_CRM_API->getStatusCode() != 200) {
+ if ($this->INTARO_CRM_API->getStatusCode() != 201) {
+ //handle err
+ ICrmOrderActions::eventLog('install/index.php', 'IntaroCrm\RestApi::deliveryTypeEdit', $this->INTARO_CRM_API->getLastError());
+ }
+ }
+ } while ($arDeliveryTypesList = $dbDeliveryTypesList->Fetch());
+ }
+ }
+
+ //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']] = 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"
+ )
+ );
+
+ //form payment statuses ids arr
+ $paymentStatusesArr['YY'] = htmlspecialchars(trim($_POST['payment-status-YY']));
+
+ if ($arPaymentStatusesList = $dbPaymentStatusesList->Fetch()) {
+ do {
+ $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']));
+
+ //form orderProps
+ $dbProp = CSaleOrderProps::GetList(array(), array());
+ while ($arProp = $dbProp->GetNext()) {
+ $arResult['arProp'][$arProp['PERSON_TYPE_ID']][] = $arProp;
+ }
+
+ 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_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);
+ COption::SetOptionString($this->MODULE_ID, $this->CRM_ORDER_DISCHARGE, 0);
+ COption::SetOptionString($this->MODULE_ID, $this->CRM_ORDER_FAILED_IDS, serialize(array()));
+ COption::SetOptionString($this->MODULE_ID, $this->CRM_ORDER_HISTORY_DATE, date('Y-m-d H:i:s'));
+
+ $APPLICATION->IncludeAdminFile(
+ GetMessage('MODULE_INSTALL_TITLE'),
+ $_SERVER['DOCUMENT_ROOT'] . '/bitrix/modules/' . $this->MODULE_ID . '/install/step3.php'
+ );
+ } else if ($step == 4) {
+ if (!CModule::IncludeModule("sale")) {
+ //handler
+ }
+
+ if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && (strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest')
+ && isset($_POST['ajax']) && ($_POST['ajax'] == 1)) {
+ ICrmOrderActions::uploadOrders(); // each 50
+
+ $lastUpOrderId = COption::GetOptionString($this->MODULE_ID, $this->CRM_ORDER_LAST_ID, 0);
+ $countLeft = (int) CSaleOrder::GetList(array("ID" => "ASC"), array('>ID' => $lastUpOrderId), array());
+ $countAll = (int) CSaleOrder::GetList(array("ID" => "ASC"), array(), array());
+
+ if (!isset($_POST['finish']))
+ $finish = 0;
+ else
+ $finish = (int) $_POST['finish'];
+
+ $percent = round(100 - ($countLeft * 100 / $countAll), 1);
+
+ if (!$countLeft)
+ $finish = 1;
+
+ $APPLICATION->RestartBuffer();
+ header('Content-Type: application/x-javascript; charset=' . LANG_CHARSET);
+ die(json_encode(array("finish" => $finish, "percent" => $percent)));
+ }
+
+ if (isset($_POST['back']) && $_POST['back']) {
+ $APPLICATION->IncludeAdminFile(
+ GetMessage('MODULE_INSTALL_TITLE'), $_SERVER['DOCUMENT_ROOT'] . '/bitrix/modules/' . $this->MODULE_ID . '/install/step2.php'
+ );
+ }
+
+ //bitrix orderTypesList -- personTypes
+ $dbOrderTypesList = CSalePersonType::GetList(
+ array(
+ "SORT" => "ASC",
+ "NAME" => "ASC"
+ ), array(
+ "ACTIVE" => "Y",
+ ), false, false, array()
+ );
+
+ //form order types ids arr
+ $orderTypesArr = array();
+ $orderTypesList = array();
+ if ($arOrderTypesList = $dbOrderTypesList->Fetch()) {
+ do {
+ $orderTypesArr[$arOrderTypesList['ID']] = htmlspecialchars(trim($_POST['order-type-' . $arOrderTypesList['ID']]));
+ $orderTypesList[] = $arOrderTypesList;
+ } while ($arOrderTypesList = $dbOrderTypesList->Fetch());
+ }
+
+ $orderPropsArr = array();
+ foreach ($orderTypesList as $orderType) {
+ $propsCount = 0;
+ $_orderPropsArr = array();
+ foreach ($arResult['orderProps'] as $orderProp) {
+ if ((!(int) htmlspecialchars(trim($_POST['address-detail-' . $orderType['ID']]))) && $propsCount > 4)
+ break;
+ $_orderPropsArr[$orderProp['ID']] = htmlspecialchars(trim($_POST['order-prop-' . $orderProp['ID'] . '-' . $orderType['ID']]));
+ $propsCount++;
+ }
+ $orderPropsArr[$orderType['ID']] = $_orderPropsArr;
+ }
+
+ COption::SetOptionString($this->MODULE_ID, $this->CRM_ORDER_PROPS, serialize($orderPropsArr));
+
+ $APPLICATION->IncludeAdminFile(
+ GetMessage('MODULE_INSTALL_TITLE'),
+ $_SERVER['DOCUMENT_ROOT'] . '/bitrix/modules/' . $this->MODULE_ID . '/install/step4.php'
+ );
+
+ } else if ($step == 5) {
+ if (!CModule::IncludeModule("iblock")) {
+ $arResult['errCode'] = 'ERR_IBLOCK';
+ }
+
+ if (!CModule::IncludeModule("catalog")) {
+ $arResult['errCode'] = 'ERR_CATALOG';
+ }
+ $APPLICATION->IncludeAdminFile(
+ GetMessage('MODULE_INSTALL_TITLE'),
+ $_SERVER['DOCUMENT_ROOT'] . '/bitrix/modules/' . $this->MODULE_ID . '/install/step5.php'
+ );
+ } else if ($step == 6) {
+
+ if (!CModule::IncludeModule("iblock")) {
+ $arResult['errCode'] = 'ERR_IBLOCK';
+ }
+
+ if (!CModule::IncludeModule("catalog")) {
+ $arResult['errCode'] = 'ERR_CATALOG';
+ }
+
+ if (isset($arResult['errCode']) && $arResult['errCode']) {
+ $APPLICATION->IncludeAdminFile(
+ GetMessage('MODULE_INSTALL_TITLE'),
+ $_SERVER['DOCUMENT_ROOT'] . '/bitrix/modules/' . $this->MODULE_ID . '/install/step5.php'
+ );
+ return;
+ }
+
+ if (isset($_POST['back']) && $_POST['back']) {
+ $APPLICATION->IncludeAdminFile(
+ GetMessage('MODULE_INSTALL_TITLE'),
+ $_SERVER['DOCUMENT_ROOT'] . '/bitrix/modules/' . $this->MODULE_ID . '/install/step3.php'
+ );
+ }
+
+ if (!isset($_POST['IBLOCK_EXPORT']))
+ $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['SETUP_FILE_NAME']))
+ $arResult['errCode'] = 'ERR_FIELDS_FILE';
+ else
+ $filename = $_POST['SETUP_FILE_NAME'];
+
+ if (!isset($_POST['TYPE_LOADING']))
+ $typeLoading = 0;
+ else
+ $typeLoading = $_POST['TYPE_LOADING'];
+
+ if (!isset($_POST['SETUP_PROFILE_NAME']))
+ $profileName = "";
+ else
+ $profileName = $_POST['SETUP_PROFILE_NAME'];
+
+ if ($typeLoading != 'none' && $profileName == "")
+ $arResult['errCode'] = 'ERR_FIELDS_PROFILE';
+
+ if ($filename == "")
+ $arResult['errCode'] = 'ERR_FIELDS_FILE';
+
+ if (isset($arResult['errCode']) && $arResult['errCode']) {
+
+ $arOldValues = Array(
+ 'IBLOCK_EXPORT' => $iblocks,
+ 'IBLOCK_PROPERTY_SKU' => $propertiesSKU,
+ 'IBLOCK_PROPERTY_PRODUCT' => $propertiesProduct,
+ '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'
+ );
+ return;
+ }
+
+ RegisterModule($this->MODULE_ID);
+ RegisterModuleDependences("sale", "OnSalePayOrder", $this->MODULE_ID, "ICrmOrderEvent", "onSalePayOrder");
+ RegisterModuleDependences("sale", "OnSaleCancelOrder", $this->MODULE_ID, "ICrmOrderEvent", "onSaleCancelOrder");
+ RegisterModuleDependences("sale", "OnBeforeOrderAccountNumberSet", $this->MODULE_ID, "ICrmOrderEvent", "onBeforeOrderAccountNumberSet");
+ $this->CopyFiles();
+ if (isset($_POST['LOAD_NOW'])) {
+
+ $loader = new ICMLLoader();
+ $loader->iblocks = $iblocks;
+ $loader->propertiesProduct = $propertiesProduct;
+ $loader->propertiesSKU = $propertiesSKU;
+ $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));
+
+ while ($arProfile = $dbProfile->Fetch()) {
+ if ($arProfile["DEFAULT_PROFILE"] != "Y") {
+ CAgent::RemoveAgent("CCatalogExport::PreGenerateExport(" . $arProfile['ID'] . ");", "catalog");
+ CCatalogExport::Delete($arProfile['ID']);
+ }
+ }
+ }
+ $ar = $this->GetProfileSetupVars($iblocks, $propertiesProduct, $propertiesSKU, $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
+ ));
+ if (intval($PROFILE_ID) <= 0) {
+ $arResult['errCode'] = 'ERR_IBLOCK';
+ return;
+ }
+ if ($typeLoading == 'agent') {
+
+ $dateAgent = new DateTime();
+ $intAgent = new DateInterval('PT60S'); // PT60S - 60 sec;
+ $dateAgent->add($intAgent);
+ CAgent::AddAgent(
+ "CCatalogExport::PreGenerateExport(" . $PROFILE_ID . ");", "catalog", "N", 86400, $dateAgent->format('d.m.Y H:i:s'), // date of first check
+ "Y", // agent is active
+ $dateAgent->format('d.m.Y H:i:s'), // date of first start
+ 30
+ );
+
+ CCatalogExport::Update($PROFILE_ID, array(
+ "IN_AGENT" => "Y"
+ ));
+ } else {
+ $agent_period = 24;
+ $agent_php_path = "/usr/local/php/bin/php";
+
+ if (!file_exists($_SERVER["DOCUMENT_ROOT"] . CATALOG_PATH2EXPORTS . "cron_frame.php")) {
+ CheckDirPath($_SERVER["DOCUMENT_ROOT"] . CATALOG_PATH2EXPORTS);
+ $tmp_file_size = filesize($_SERVER["DOCUMENT_ROOT"] . CATALOG_PATH2EXPORTS_DEF . "cron_frame.php");
+ $fp = fopen($_SERVER["DOCUMENT_ROOT"] . CATALOG_PATH2EXPORTS_DEF . "cron_frame.php", "rb");
+ $tmp_data = fread($fp, $tmp_file_size);
+ fclose($fp);
+
+ $tmp_data = str_replace("#DOCUMENT_ROOT#", $_SERVER["DOCUMENT_ROOT"], $tmp_data);
+ $tmp_data = str_replace("#PHP_PATH#", $agent_php_path, $tmp_data);
+
+ $fp = fopen($_SERVER["DOCUMENT_ROOT"] . CATALOG_PATH2EXPORTS . "cron_frame.php", "ab");
+ fwrite($fp, $tmp_data);
+ fclose($fp);
+ }
+
+ $cfg_data = "";
+ if (file_exists($_SERVER["DOCUMENT_ROOT"] . "/bitrix/crontab/crontab.cfg")) {
+ $cfg_file_size = filesize($_SERVER["DOCUMENT_ROOT"] . "/bitrix/crontab/crontab.cfg");
+ $fp = fopen($_SERVER["DOCUMENT_ROOT"] . "/bitrix/crontab/crontab.cfg", "rb");
+ $cfg_data = fread($fp, $cfg_file_size);
+ fclose($fp);
+ }
+
+ CheckDirPath($_SERVER["DOCUMENT_ROOT"] . CATALOG_PATH2EXPORTS . "logs/");
+
+ if ($arProfile["IN_CRON"] == "Y") {
+ // remove
+ $cfg_data = preg_replace("#^.*?" . preg_quote(CATALOG_PATH2EXPORTS) . "cron_frame.php +" . $PROFILE_ID . " *>.*?$#im", "", $cfg_data);
+ } else {
+ $strTime = "0 */" . $agent_period . " * * * ";
+ if (strlen($cfg_data) > 0)
+ $cfg_data .= "\n";
+
+ $cfg_data .= $strTime . $agent_php_path . " -f " . $_SERVER["DOCUMENT_ROOT"] . CATALOG_PATH2EXPORTS . "cron_frame.php " . $PROFILE_ID . " >" . $_SERVER["DOCUMENT_ROOT"] . CATALOG_PATH2EXPORTS . "logs/" . $PROFILE_ID . ".txt\n";
+ }
+
+ CCatalogExport::Update($PROFILE_ID, array(
+ "IN_CRON" => "Y"
+ ));
+
+ CheckDirPath($_SERVER["DOCUMENT_ROOT"] . "/bitrix/crontab/");
+ $cfg_data = preg_replace("#[\r\n]{2,}#im", "\n", $cfg_data);
+ $fp = fopen($_SERVER["DOCUMENT_ROOT"] . "/bitrix/crontab/crontab.cfg", "wb");
+ fwrite($fp, $cfg_data);
+ fclose($fp);
+
+ $arRetval = array();
+ @exec("crontab " . $_SERVER["DOCUMENT_ROOT"] . "/bitrix/crontab/crontab.cfg", $arRetval, $return_var);
+ }
+ }
+
+ //agent
+
+ $dateAgent = new DateTime();
+ $intAgent = new DateInterval('PT60S'); // PT60S - 60 sec;
+ $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", // agent is active
+ $dateAgent->format('d.m.Y H:i:s'), // date of first start
+ 30
+ );
+
+ CAgent::AddAgent(
+ "ICrmOrderActions::orderHistoryAgent();",
+ $this->MODULE_ID,
+ "N",
+ 600, // interval - 10 mins
+ $dateAgent->format('d.m.Y H:i:s'), // date of first check
+ "Y", // agent is active
+ $dateAgent->format('d.m.Y H:i:s'), // date of first start
+ 30
+ );
+
+ $api_host = COption::GetOptionString($this->MODULE_ID, $this->CRM_API_HOST_OPTION, 0);
+ $api_key = COption::GetOptionString($this->MODULE_ID, $this->CRM_API_KEY_OPTION, 0);
+ $this->INTARO_CRM_API = new \IntaroCrm\RestApi($api_host, $api_key);
+ $this->INTARO_CRM_API->statisticUpdate();
+
+ $APPLICATION->IncludeAdminFile(
+ GetMessage('MODULE_INSTALL_TITLE'),
+ $_SERVER['DOCUMENT_ROOT'] . '/bitrix/modules/' . $this->MODULE_ID . '/install/step6.php'
+ );
+ }
+ }
+
+ function DoUninstall() {
+ global $APPLICATION;
+
+ CAgent::RemoveAgent("ICrmOrderActions::uploadOrdersAgent();", $this->MODULE_ID);
+ CAgent::RemoveAgent("ICrmOrderActions::orderHistoryAgent();", $this->MODULE_ID);
+
+ COption::RemoveOption($this->MODULE_ID, $this->CRM_API_HOST_OPTION);
+ COption::RemoveOption($this->MODULE_ID, $this->CRM_API_KEY_OPTION);
+ 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);
+ COption::RemoveOption($this->MODULE_ID, $this->CRM_ORDER_LAST_ID);
+ COption::RemoveOption($this->MODULE_ID, $this->CRM_ORDER_SITES);
+ COption::RemoveOption($this->MODULE_ID, $this->CRM_ORDER_PROPS);
+ COption::RemoveOption($this->MODULE_ID, $this->CRM_ORDER_DISCHARGE);
+ COption::RemoveOption($this->MODULE_ID, $this->CRM_ORDER_FAILED_IDS);
+ COption::RemoveOption($this->MODULE_ID, $this->CRM_ORDER_HISTORY_DATE);
+
+ UnRegisterModuleDependences("sale", "OnSalePayOrder", $this->MODULE_ID, "ICrmOrderEvent", "onSalePayOrder");
+ UnRegisterModuleDependences("sale", "OnSaleCancelOrder", $this->MODULE_ID, "ICrmOrderEvent", "onSaleCancelOrder");
+ UnRegisterModuleDependences("sale", "OnOrderNewSendEmail", $this->MODULE_ID, "ICrmOrderEvent", "onSendOrderMail");
+ UnRegisterModuleDependences("sale", "OnOrderUpdate", $this->MODULE_ID, "ICrmOrderEvent", "onUpdateOrder");
+ UnRegisterModuleDependences("sale", "OnBeforeOrderAdd", $this->MODULE_ID, "ICrmOrderEvent", "onBeforeOrderAdd");
+ UnRegisterModuleDependences("sale", "OnBeforeOrderAccountNumberSet", $this->MODULE_ID, "ICrmOrderEvent", "onBeforeOrderAccountNumberSet");
+ if (CModule::IncludeModule("catalog")) {
+ 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));
+
+ while ($arProfile = $dbProfile->Fetch()) {
+ if ($arProfile["DEFAULT_PROFILE"] != "Y") {
+ CAgent::RemoveAgent("CCatalogExport::PreGenerateExport(" . $arProfile['ID'] . ");", "catalog");
+ CCatalogExport::Delete($arProfile['ID']);
+ }
+ }
+ }
+ }
+
+ $this->DeleteFiles();
+
+ UnRegisterModule($this->MODULE_ID);
+
+ $APPLICATION->IncludeAdminFile(
+ GetMessage('MODULE_UNINSTALL_TITLE'), $_SERVER['DOCUMENT_ROOT'] . '/bitrix/modules/' . $this->MODULE_ID . '/install/unstep1.php'
+ );
+ }
+
+ function CopyFiles() {
+ CopyDirFiles(
+ $_SERVER['DOCUMENT_ROOT'] . '/bitrix/modules/' . $this->MODULE_ID . '/install/export/', $_SERVER['DOCUMENT_ROOT'] . '/bitrix/php_interface/include/catalog_export/', true, true
+ );
+ }
+
+ function DeleteFiles() {
+ unlink($_SERVER['DOCUMENT_ROOT'] . '/bitrix/php_interface/include/catalog_export/intarocrm_run.php');
+ unlink($_SERVER['DOCUMENT_ROOT'] . '/bitrix/php_interface/include/catalog_export/intarocrm_setup.php');
+ }
+
+ function GetProfileSetupVars($iblocks, $propertiesProduct, $propertiesSKU, $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)
+ $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 . '&';
+
+ $strVars .= 'SETUP_FILE_NAME=' . urlencode($filename);
+
+ return $strVars;
+ }
}
\ No newline at end of file
diff --git a/intaro.intarocrm/install/version.php b/intaro.intarocrm/install/version.php
index d43cd123..2eb60667 100644
--- a/intaro.intarocrm/install/version.php
+++ b/intaro.intarocrm/install/version.php
@@ -1,5 +1,5 @@
$arModuleVersion = array(
"VERSION" => "0.4.3",
- "VERSION_DATE" => "2013-10-29 15:28:00",
+ "VERSION_DATE" => "2013-10-30 16:04:00",
);
\ No newline at end of file